Add some additional channel-creation-broadcast-msg sanity checks
[rust-lightning] / src / ln / channelmanager.rs
1 //! The top-level channel management and payment tracking stuff lives here.
2 //!
3 //! The ChannelManager is the main chunk of logic implementing the lightning protocol and is
4 //! responsible for tracking which channels are open, HTLCs are in flight and reestablishing those
5 //! upon reconnect to the relevant peer(s).
6 //!
7 //! It does not manage routing logic (see ln::router for that) nor does it manage constructing
8 //! on-chain transactions (it only monitors the chain to watch for any force-closes that might
9 //! imply it needs to fail HTLCs/payments/channels it manages).
10
11 use bitcoin::blockdata::block::BlockHeader;
12 use bitcoin::blockdata::transaction::Transaction;
13 use bitcoin::blockdata::constants::genesis_block;
14 use bitcoin::network::constants::Network;
15 use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
16
17 use secp256k1::key::{SecretKey,PublicKey};
18 use secp256k1::{Secp256k1,Message};
19 use secp256k1::ecdh::SharedSecret;
20 use secp256k1;
21
22 use chain::chaininterface::{BroadcasterInterface,ChainListener,ChainWatchInterface,FeeEstimator};
23 use chain::transaction::OutPoint;
24 use ln::channel::{Channel, ChannelError};
25 use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, ManyChannelMonitor, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, HTLC_FAIL_ANTI_REORG_DELAY};
26 use ln::router::{Route,RouteHop};
27 use ln::msgs;
28 use ln::msgs::{ChannelMessageHandler, DecodeError, HandleError};
29 use chain::keysinterface::KeysInterface;
30 use util::config::UserConfig;
31 use util::{byte_utils, events, internal_traits, rng};
32 use util::sha2::Sha256;
33 use util::ser::{Readable, ReadableArgs, Writeable, Writer};
34 use util::chacha20poly1305rfc::ChaCha20;
35 use util::logger::Logger;
36 use util::errors::APIError;
37 use util::errors;
38
39 use crypto;
40 use crypto::mac::{Mac,MacResult};
41 use crypto::hmac::Hmac;
42 use crypto::digest::Digest;
43 use crypto::symmetriccipher::SynchronousStreamCipher;
44
45 use std::{cmp, ptr, mem};
46 use std::collections::{HashMap, hash_map, HashSet};
47 use std::io::Cursor;
48 use std::sync::{Arc, Mutex, MutexGuard, RwLock};
49 use std::sync::atomic::{AtomicUsize, Ordering};
50 use std::time::{Instant,Duration};
51
52 /// We hold various information about HTLC relay in the HTLC objects in Channel itself:
53 ///
54 /// Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
55 /// forward the HTLC with information it will give back to us when it does so, or if it should Fail
56 /// the HTLC with the relevant message for the Channel to handle giving to the remote peer.
57 ///
58 /// When a Channel forwards an HTLC to its peer, it will give us back the PendingForwardHTLCInfo
59 /// which we will use to construct an outbound HTLC, with a relevant HTLCSource::PreviousHopData
60 /// filled in to indicate where it came from (which we can use to either fail-backwards or fulfill
61 /// the HTLC backwards along the relevant path).
62 /// Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
63 /// our payment, which we can use to decode errors or inform the user that the payment was sent.
64 mod channel_held_info {
65         use ln::msgs;
66         use ln::router::Route;
67         use ln::channelmanager::PaymentHash;
68         use secp256k1::key::SecretKey;
69
70         /// Stores the info we will need to send when we want to forward an HTLC onwards
71         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
72         pub struct PendingForwardHTLCInfo {
73                 pub(super) onion_packet: Option<msgs::OnionPacket>,
74                 pub(super) incoming_shared_secret: [u8; 32],
75                 pub(super) payment_hash: PaymentHash,
76                 pub(super) short_channel_id: u64,
77                 pub(super) amt_to_forward: u64,
78                 pub(super) outgoing_cltv_value: u32,
79         }
80
81         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
82         pub enum HTLCFailureMsg {
83                 Relay(msgs::UpdateFailHTLC),
84                 Malformed(msgs::UpdateFailMalformedHTLC),
85         }
86
87         /// Stores whether we can't forward an HTLC or relevant forwarding info
88         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
89         pub enum PendingHTLCStatus {
90                 Forward(PendingForwardHTLCInfo),
91                 Fail(HTLCFailureMsg),
92         }
93
94         /// Tracks the inbound corresponding to an outbound HTLC
95         #[derive(Clone, PartialEq)]
96         pub struct HTLCPreviousHopData {
97                 pub(super) short_channel_id: u64,
98                 pub(super) htlc_id: u64,
99                 pub(super) incoming_packet_shared_secret: [u8; 32],
100         }
101
102         /// Tracks the inbound corresponding to an outbound HTLC
103         #[derive(Clone, PartialEq)]
104         pub enum HTLCSource {
105                 PreviousHopData(HTLCPreviousHopData),
106                 OutboundRoute {
107                         route: Route,
108                         session_priv: SecretKey,
109                         /// Technically we can recalculate this from the route, but we cache it here to avoid
110                         /// doing a double-pass on route when we get a failure back
111                         first_hop_htlc_msat: u64,
112                 },
113         }
114         #[cfg(test)]
115         impl HTLCSource {
116                 pub fn dummy() -> Self {
117                         HTLCSource::OutboundRoute {
118                                 route: Route { hops: Vec::new() },
119                                 session_priv: SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[1; 32]).unwrap(),
120                                 first_hop_htlc_msat: 0,
121                         }
122                 }
123         }
124
125         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
126         pub(crate) enum HTLCFailReason {
127                 ErrorPacket {
128                         err: msgs::OnionErrorPacket,
129                 },
130                 Reason {
131                         failure_code: u16,
132                         data: Vec<u8>,
133                 }
134         }
135 }
136 pub(super) use self::channel_held_info::*;
137
138 /// payment_hash type, use to cross-lock hop
139 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
140 pub struct PaymentHash(pub [u8;32]);
141 /// payment_preimage type, use to route payment between hop
142 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
143 pub struct PaymentPreimage(pub [u8;32]);
144
145 type ShutdownResult = (Vec<Transaction>, Vec<(HTLCSource, PaymentHash)>);
146
147 /// Error type returned across the channel_state mutex boundary. When an Err is generated for a
148 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
149 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
150 /// channel_state lock. We then return the set of things that need to be done outside the lock in
151 /// this struct and call handle_error!() on it.
152
153 struct MsgHandleErrInternal {
154         err: msgs::HandleError,
155         shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
156 }
157 impl MsgHandleErrInternal {
158         #[inline]
159         fn send_err_msg_no_close(err: &'static str, channel_id: [u8; 32]) -> Self {
160                 Self {
161                         err: HandleError {
162                                 err,
163                                 action: Some(msgs::ErrorAction::SendErrorMessage {
164                                         msg: msgs::ErrorMessage {
165                                                 channel_id,
166                                                 data: err.to_string()
167                                         },
168                                 }),
169                         },
170                         shutdown_finish: None,
171                 }
172         }
173         #[inline]
174         fn from_no_close(err: msgs::HandleError) -> Self {
175                 Self { err, shutdown_finish: None }
176         }
177         #[inline]
178         fn from_finish_shutdown(err: &'static str, channel_id: [u8; 32], shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
179                 Self {
180                         err: HandleError {
181                                 err,
182                                 action: Some(msgs::ErrorAction::SendErrorMessage {
183                                         msg: msgs::ErrorMessage {
184                                                 channel_id,
185                                                 data: err.to_string()
186                                         },
187                                 }),
188                         },
189                         shutdown_finish: Some((shutdown_res, channel_update)),
190                 }
191         }
192         #[inline]
193         fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
194                 Self {
195                         err: match err {
196                                 ChannelError::Ignore(msg) => HandleError {
197                                         err: msg,
198                                         action: Some(msgs::ErrorAction::IgnoreError),
199                                 },
200                                 ChannelError::Close(msg) => HandleError {
201                                         err: msg,
202                                         action: Some(msgs::ErrorAction::SendErrorMessage {
203                                                 msg: msgs::ErrorMessage {
204                                                         channel_id,
205                                                         data: msg.to_string()
206                                                 },
207                                         }),
208                                 },
209                         },
210                         shutdown_finish: None,
211                 }
212         }
213 }
214
215 /// Pass to fail_htlc_backwwards to indicate the reason to fail the payment
216 /// after a PaymentReceived event.
217 #[derive(PartialEq)]
218 pub enum PaymentFailReason {
219         /// Indicate the preimage for payment_hash is not known after a PaymentReceived event
220         PreimageUnknown,
221         /// Indicate the payment amount is incorrect ( received is < expected or > 2*expected ) after a PaymentReceived event
222         AmountMismatch,
223 }
224
225 /// We hold back HTLCs we intend to relay for a random interval in the range (this, 5*this). This
226 /// provides some limited amount of privacy. Ideally this would range from somewhere like 1 second
227 /// to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly. We could
228 /// probably increase this significantly.
229 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
230
231 struct HTLCForwardInfo {
232         prev_short_channel_id: u64,
233         prev_htlc_id: u64,
234         forward_info: PendingForwardHTLCInfo,
235 }
236
237 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
238 /// be sent in the order they appear in the return value, however sometimes the order needs to be
239 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
240 /// they were originally sent). In those cases, this enum is also returned.
241 #[derive(Clone, PartialEq)]
242 pub(super) enum RAACommitmentOrder {
243         /// Send the CommitmentUpdate messages first
244         CommitmentFirst,
245         /// Send the RevokeAndACK message first
246         RevokeAndACKFirst,
247 }
248
249 struct ChannelHolder {
250         by_id: HashMap<[u8; 32], Channel>,
251         short_to_id: HashMap<u64, [u8; 32]>,
252         next_forward: Instant,
253         /// short channel id -> forward infos. Key of 0 means payments received
254         /// Note that while this is held in the same mutex as the channels themselves, no consistency
255         /// guarantees are made about there existing a channel with the short id here, nor the short
256         /// ids in the PendingForwardHTLCInfo!
257         forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
258         /// Note that while this is held in the same mutex as the channels themselves, no consistency
259         /// guarantees are made about the channels given here actually existing anymore by the time you
260         /// go to read them!
261         claimable_htlcs: HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
262         /// Messages to send to peers - pushed to in the same lock that they are generated in (except
263         /// for broadcast messages, where ordering isn't as strict).
264         pending_msg_events: Vec<events::MessageSendEvent>,
265 }
266 struct MutChannelHolder<'a> {
267         by_id: &'a mut HashMap<[u8; 32], Channel>,
268         short_to_id: &'a mut HashMap<u64, [u8; 32]>,
269         next_forward: &'a mut Instant,
270         forward_htlcs: &'a mut HashMap<u64, Vec<HTLCForwardInfo>>,
271         claimable_htlcs: &'a mut HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
272         pending_msg_events: &'a mut Vec<events::MessageSendEvent>,
273 }
274 impl ChannelHolder {
275         fn borrow_parts(&mut self) -> MutChannelHolder {
276                 MutChannelHolder {
277                         by_id: &mut self.by_id,
278                         short_to_id: &mut self.short_to_id,
279                         next_forward: &mut self.next_forward,
280                         forward_htlcs: &mut self.forward_htlcs,
281                         claimable_htlcs: &mut self.claimable_htlcs,
282                         pending_msg_events: &mut self.pending_msg_events,
283                 }
284         }
285 }
286
287 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
288 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
289
290 /// Manager which keeps track of a number of channels and sends messages to the appropriate
291 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
292 ///
293 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
294 /// to individual Channels.
295 ///
296 /// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
297 /// all peers during write/read (though does not modify this instance, only the instance being
298 /// serialized). This will result in any channels which have not yet exchanged funding_created (ie
299 /// called funding_transaction_generated for outbound channels).
300 ///
301 /// Note that you can be a bit lazier about writing out ChannelManager than you can be with
302 /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
303 /// returning from ManyChannelMonitor::add_update_monitor, with ChannelManagers, writing updates
304 /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during
305 /// the serialization process). If the deserialized version is out-of-date compared to the
306 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
307 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
308 ///
309 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelManager), which
310 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
311 /// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
312 /// block_connected() to step towards your best block) upon deserialization before using the
313 /// object!
314 pub struct ChannelManager {
315         default_configuration: UserConfig,
316         genesis_hash: Sha256dHash,
317         fee_estimator: Arc<FeeEstimator>,
318         monitor: Arc<ManyChannelMonitor>,
319         chain_monitor: Arc<ChainWatchInterface>,
320         tx_broadcaster: Arc<BroadcasterInterface>,
321
322         latest_block_height: AtomicUsize,
323         last_block_hash: Mutex<Sha256dHash>,
324         secp_ctx: Secp256k1<secp256k1::All>,
325
326         channel_state: Mutex<ChannelHolder>,
327         our_network_key: SecretKey,
328
329         pending_events: Mutex<Vec<events::Event>>,
330         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
331         /// Essentially just when we're serializing ourselves out.
332         /// Taken first everywhere where we are making changes before any other locks.
333         total_consistency_lock: RwLock<()>,
334
335         keys_manager: Arc<KeysInterface>,
336
337         logger: Arc<Logger>,
338 }
339
340 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
341 /// HTLC's CLTV. This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
342 /// ie the node we forwarded the payment on to should always have enough room to reliably time out
343 /// the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
344 /// CLTV_CLAIM_BUFFER point (we static assert that its at least 3 blocks more).
345 const CLTV_EXPIRY_DELTA: u16 = 6 * 12; //TODO?
346 const CLTV_FAR_FAR_AWAY: u32 = 6 * 24 * 7; //TODO?
347
348 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + 2*HTLC_FAIL_TIMEOUT_BLOCKS +
349 // HTLC_FAIL_ANTI_REORG_DELAY, ie that if the next-hop peer fails the HTLC within
350 // HTLC_FAIL_TIMEOUT_BLOCKS then we'll still have HTLC_FAIL_TIMEOUT_BLOCKS left to fail it
351 // backwards ourselves before hitting the CLTV_CLAIM_BUFFER point and failing the channel
352 // on-chain to time out the HTLC.
353 #[deny(const_err)]
354 #[allow(dead_code)]
355 const CHECK_CLTV_EXPIRY_SANITY: u32 = CLTV_EXPIRY_DELTA as u32 - 2*HTLC_FAIL_TIMEOUT_BLOCKS - CLTV_CLAIM_BUFFER - HTLC_FAIL_ANTI_REORG_DELAY;
356
357 // Check for ability of an attacker to make us fail on-chain by delaying inbound claim. See
358 // ChannelMontior::would_broadcast_at_height for a description of why this is needed.
359 #[deny(const_err)]
360 #[allow(dead_code)]
361 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = CLTV_EXPIRY_DELTA as u32 - HTLC_FAIL_TIMEOUT_BLOCKS - 2*CLTV_CLAIM_BUFFER;
362
363 macro_rules! secp_call {
364         ( $res: expr, $err: expr ) => {
365                 match $res {
366                         Ok(key) => key,
367                         Err(_) => return Err($err),
368                 }
369         };
370 }
371
372 struct OnionKeys {
373         #[cfg(test)]
374         shared_secret: SharedSecret,
375         #[cfg(test)]
376         blinding_factor: [u8; 32],
377         ephemeral_pubkey: PublicKey,
378         rho: [u8; 32],
379         mu: [u8; 32],
380 }
381
382 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
383 pub struct ChannelDetails {
384         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
385         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
386         /// Note that this means this value is *not* persistent - it can change once during the
387         /// lifetime of the channel.
388         pub channel_id: [u8; 32],
389         /// The position of the funding transaction in the chain. None if the funding transaction has
390         /// not yet been confirmed and the channel fully opened.
391         pub short_channel_id: Option<u64>,
392         /// The node_id of our counterparty
393         pub remote_network_id: PublicKey,
394         /// The value, in satoshis, of this channel as appears in the funding output
395         pub channel_value_satoshis: u64,
396         /// The user_id passed in to create_channel, or 0 if the channel was inbound.
397         pub user_id: u64,
398 }
399
400 macro_rules! handle_error {
401         ($self: ident, $internal: expr, $their_node_id: expr) => {
402                 match $internal {
403                         Ok(msg) => Ok(msg),
404                         Err(MsgHandleErrInternal { err, shutdown_finish }) => {
405                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
406                                         $self.finish_force_close_channel(shutdown_res);
407                                         if let Some(update) = update_option {
408                                                 let mut channel_state = $self.channel_state.lock().unwrap();
409                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
410                                                         msg: update
411                                                 });
412                                         }
413                                 }
414                                 Err(err)
415                         },
416                 }
417         }
418 }
419
420 macro_rules! break_chan_entry {
421         ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
422                 match $res {
423                         Ok(res) => res,
424                         Err(ChannelError::Ignore(msg)) => {
425                                 break Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
426                         },
427                         Err(ChannelError::Close(msg)) => {
428                                 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
429                                 let (channel_id, mut chan) = $entry.remove_entry();
430                                 if let Some(short_id) = chan.get_short_channel_id() {
431                                         $channel_state.short_to_id.remove(&short_id);
432                                 }
433                                 break Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
434                         },
435                 }
436         }
437 }
438
439 macro_rules! try_chan_entry {
440         ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
441                 match $res {
442                         Ok(res) => res,
443                         Err(ChannelError::Ignore(msg)) => {
444                                 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
445                         },
446                         Err(ChannelError::Close(msg)) => {
447                                 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
448                                 let (channel_id, mut chan) = $entry.remove_entry();
449                                 if let Some(short_id) = chan.get_short_channel_id() {
450                                         $channel_state.short_to_id.remove(&short_id);
451                                 }
452                                 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
453                         },
454                 }
455         }
456 }
457
458 macro_rules! return_monitor_err {
459         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
460                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new())
461         };
462         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $raa_first_dropped_cs: expr) => {
463                 if $action_type != RAACommitmentOrder::RevokeAndACKFirst { panic!("Bad return_monitor_err call!"); }
464                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new(), $raa_first_dropped_cs)
465         };
466         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr) => {
467                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, $failed_forwards, $failed_fails, false)
468         };
469         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr, $raa_first_dropped_cs: expr) => {
470                 match $err {
471                         ChannelMonitorUpdateErr::PermanentFailure => {
472                                 let (channel_id, mut chan) = $entry.remove_entry();
473                                 if let Some(short_id) = chan.get_short_channel_id() {
474                                         $channel_state.short_to_id.remove(&short_id);
475                                 }
476                                 // TODO: $failed_fails is dropped here, which will cause other channels to hit the
477                                 // chain in a confused state! We need to move them into the ChannelMonitor which
478                                 // will be responsible for failing backwards once things confirm on-chain.
479                                 // It's ok that we drop $failed_forwards here - at this point we'd rather they
480                                 // broadcast HTLC-Timeout and pay the associated fees to get their funds back than
481                                 // us bother trying to claim it just to forward on to another peer. If we're
482                                 // splitting hairs we'd prefer to claim payments that were to us, but we haven't
483                                 // given up the preimage yet, so might as well just wait until the payment is
484                                 // retried, avoiding the on-chain fees.
485                                 return Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
486                         },
487                         ChannelMonitorUpdateErr::TemporaryFailure => {
488                                 $entry.get_mut().monitor_update_failed($action_type, $failed_forwards, $failed_fails, $raa_first_dropped_cs);
489                                 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore("Failed to update ChannelMonitor"), *$entry.key()));
490                         },
491                 }
492         }
493 }
494
495 // Does not break in case of TemporaryFailure!
496 macro_rules! maybe_break_monitor_err {
497         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
498                 match $err {
499                         ChannelMonitorUpdateErr::PermanentFailure => {
500                                 let (channel_id, mut chan) = $entry.remove_entry();
501                                 if let Some(short_id) = chan.get_short_channel_id() {
502                                         $channel_state.short_to_id.remove(&short_id);
503                                 }
504                                 break Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
505                         },
506                         ChannelMonitorUpdateErr::TemporaryFailure => {
507                                 $entry.get_mut().monitor_update_failed($action_type, Vec::new(), Vec::new(), false);
508                         },
509                 }
510         }
511 }
512
513 impl ChannelManager {
514         /// Constructs a new ChannelManager to hold several channels and route between them.
515         ///
516         /// This is the main "logic hub" for all channel-related actions, and implements
517         /// ChannelMessageHandler.
518         ///
519         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
520         ///
521         /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
522         pub fn new(network: Network, feeest: Arc<FeeEstimator>, monitor: Arc<ManyChannelMonitor>, chain_monitor: Arc<ChainWatchInterface>, tx_broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>,keys_manager: Arc<KeysInterface>, config: UserConfig) -> Result<Arc<ChannelManager>, secp256k1::Error> {
523                 let secp_ctx = Secp256k1::new();
524
525                 let res = Arc::new(ChannelManager {
526                         default_configuration: config.clone(),
527                         genesis_hash: genesis_block(network).header.bitcoin_hash(),
528                         fee_estimator: feeest.clone(),
529                         monitor: monitor.clone(),
530                         chain_monitor,
531                         tx_broadcaster,
532
533                         latest_block_height: AtomicUsize::new(0), //TODO: Get an init value
534                         last_block_hash: Mutex::new(Default::default()),
535                         secp_ctx,
536
537                         channel_state: Mutex::new(ChannelHolder{
538                                 by_id: HashMap::new(),
539                                 short_to_id: HashMap::new(),
540                                 next_forward: Instant::now(),
541                                 forward_htlcs: HashMap::new(),
542                                 claimable_htlcs: HashMap::new(),
543                                 pending_msg_events: Vec::new(),
544                         }),
545                         our_network_key: keys_manager.get_node_secret(),
546
547                         pending_events: Mutex::new(Vec::new()),
548                         total_consistency_lock: RwLock::new(()),
549
550                         keys_manager,
551
552                         logger,
553                 });
554                 let weak_res = Arc::downgrade(&res);
555                 res.chain_monitor.register_listener(weak_res);
556                 Ok(res)
557         }
558
559         /// Creates a new outbound channel to the given remote node and with the given value.
560         ///
561         /// user_id will be provided back as user_channel_id in FundingGenerationReady and
562         /// FundingBroadcastSafe events to allow tracking of which events correspond with which
563         /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
564         /// may wish to avoid using 0 for user_id here.
565         ///
566         /// If successful, will generate a SendOpenChannel message event, so you should probably poll
567         /// PeerManager::process_events afterwards.
568         ///
569         /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
570         /// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
571         pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64) -> Result<(), APIError> {
572                 if channel_value_satoshis < 1000 {
573                         return Err(APIError::APIMisuseError { err: "channel_value must be at least 1000 satoshis" });
574                 }
575
576                 let channel = Channel::new_outbound(&*self.fee_estimator, &self.keys_manager, their_network_key, channel_value_satoshis, push_msat, user_id, Arc::clone(&self.logger), &self.default_configuration)?;
577                 let res = channel.get_open_channel(self.genesis_hash.clone(), &*self.fee_estimator);
578
579                 let _ = self.total_consistency_lock.read().unwrap();
580                 let mut channel_state = self.channel_state.lock().unwrap();
581                 match channel_state.by_id.entry(channel.channel_id()) {
582                         hash_map::Entry::Occupied(_) => {
583                                 if cfg!(feature = "fuzztarget") {
584                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG" });
585                                 } else {
586                                         panic!("RNG is bad???");
587                                 }
588                         },
589                         hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
590                 }
591                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
592                         node_id: their_network_key,
593                         msg: res,
594                 });
595                 Ok(())
596         }
597
598         /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
599         /// more information.
600         pub fn list_channels(&self) -> Vec<ChannelDetails> {
601                 let channel_state = self.channel_state.lock().unwrap();
602                 let mut res = Vec::with_capacity(channel_state.by_id.len());
603                 for (channel_id, channel) in channel_state.by_id.iter() {
604                         res.push(ChannelDetails {
605                                 channel_id: (*channel_id).clone(),
606                                 short_channel_id: channel.get_short_channel_id(),
607                                 remote_network_id: channel.get_their_node_id(),
608                                 channel_value_satoshis: channel.get_value_satoshis(),
609                                 user_id: channel.get_user_id(),
610                         });
611                 }
612                 res
613         }
614
615         /// Gets the list of usable channels, in random order. Useful as an argument to
616         /// Router::get_route to ensure non-announced channels are used.
617         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
618                 let channel_state = self.channel_state.lock().unwrap();
619                 let mut res = Vec::with_capacity(channel_state.by_id.len());
620                 for (channel_id, channel) in channel_state.by_id.iter() {
621                         // Note we use is_live here instead of usable which leads to somewhat confused
622                         // internal/external nomenclature, but that's ok cause that's probably what the user
623                         // really wanted anyway.
624                         if channel.is_live() {
625                                 res.push(ChannelDetails {
626                                         channel_id: (*channel_id).clone(),
627                                         short_channel_id: channel.get_short_channel_id(),
628                                         remote_network_id: channel.get_their_node_id(),
629                                         channel_value_satoshis: channel.get_value_satoshis(),
630                                         user_id: channel.get_user_id(),
631                                 });
632                         }
633                 }
634                 res
635         }
636
637         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
638         /// will be accepted on the given channel, and after additional timeout/the closing of all
639         /// pending HTLCs, the channel will be closed on chain.
640         ///
641         /// May generate a SendShutdown message event on success, which should be relayed.
642         pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
643                 let _ = self.total_consistency_lock.read().unwrap();
644
645                 let (mut failed_htlcs, chan_option) = {
646                         let mut channel_state_lock = self.channel_state.lock().unwrap();
647                         let channel_state = channel_state_lock.borrow_parts();
648                         match channel_state.by_id.entry(channel_id.clone()) {
649                                 hash_map::Entry::Occupied(mut chan_entry) => {
650                                         let (shutdown_msg, failed_htlcs) = chan_entry.get_mut().get_shutdown()?;
651                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
652                                                 node_id: chan_entry.get().get_their_node_id(),
653                                                 msg: shutdown_msg
654                                         });
655                                         if chan_entry.get().is_shutdown() {
656                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
657                                                         channel_state.short_to_id.remove(&short_id);
658                                                 }
659                                                 (failed_htlcs, Some(chan_entry.remove_entry().1))
660                                         } else { (failed_htlcs, None) }
661                                 },
662                                 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: "No such channel"})
663                         }
664                 };
665                 for htlc_source in failed_htlcs.drain(..) {
666                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
667                 }
668                 let chan_update = if let Some(chan) = chan_option {
669                         if let Ok(update) = self.get_channel_update(&chan) {
670                                 Some(update)
671                         } else { None }
672                 } else { None };
673
674                 if let Some(update) = chan_update {
675                         let mut channel_state = self.channel_state.lock().unwrap();
676                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
677                                 msg: update
678                         });
679                 }
680
681                 Ok(())
682         }
683
684         #[inline]
685         fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
686                 let (local_txn, mut failed_htlcs) = shutdown_res;
687                 log_trace!(self, "Finishing force-closure of channel with {} transactions to broadcast and {} HTLCs to fail", local_txn.len(), failed_htlcs.len());
688                 for htlc_source in failed_htlcs.drain(..) {
689                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
690                 }
691                 for tx in local_txn {
692                         self.tx_broadcaster.broadcast_transaction(&tx);
693                 }
694         }
695
696         /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
697         /// the chain and rejecting new HTLCs on the given channel.
698         pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
699                 let _ = self.total_consistency_lock.read().unwrap();
700
701                 let mut chan = {
702                         let mut channel_state_lock = self.channel_state.lock().unwrap();
703                         let channel_state = channel_state_lock.borrow_parts();
704                         if let Some(chan) = channel_state.by_id.remove(channel_id) {
705                                 if let Some(short_id) = chan.get_short_channel_id() {
706                                         channel_state.short_to_id.remove(&short_id);
707                                 }
708                                 chan
709                         } else {
710                                 return;
711                         }
712                 };
713                 log_trace!(self, "Force-closing channel {}", log_bytes!(channel_id[..]));
714                 self.finish_force_close_channel(chan.force_shutdown());
715                 if let Ok(update) = self.get_channel_update(&chan) {
716                         let mut channel_state = self.channel_state.lock().unwrap();
717                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
718                                 msg: update
719                         });
720                 }
721         }
722
723         /// Force close all channels, immediately broadcasting the latest local commitment transaction
724         /// for each to the chain and rejecting new HTLCs on each.
725         pub fn force_close_all_channels(&self) {
726                 for chan in self.list_channels() {
727                         self.force_close_channel(&chan.channel_id);
728                 }
729         }
730
731         #[inline]
732         fn gen_rho_mu_from_shared_secret(shared_secret: &[u8]) -> ([u8; 32], [u8; 32]) {
733                 assert_eq!(shared_secret.len(), 32);
734                 ({
735                         let mut hmac = Hmac::new(Sha256::new(), &[0x72, 0x68, 0x6f]); // rho
736                         hmac.input(&shared_secret[..]);
737                         let mut res = [0; 32];
738                         hmac.raw_result(&mut res);
739                         res
740                 },
741                 {
742                         let mut hmac = Hmac::new(Sha256::new(), &[0x6d, 0x75]); // mu
743                         hmac.input(&shared_secret[..]);
744                         let mut res = [0; 32];
745                         hmac.raw_result(&mut res);
746                         res
747                 })
748         }
749
750         #[inline]
751         fn gen_um_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
752                 assert_eq!(shared_secret.len(), 32);
753                 let mut hmac = Hmac::new(Sha256::new(), &[0x75, 0x6d]); // um
754                 hmac.input(&shared_secret[..]);
755                 let mut res = [0; 32];
756                 hmac.raw_result(&mut res);
757                 res
758         }
759
760         #[inline]
761         fn gen_ammag_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
762                 assert_eq!(shared_secret.len(), 32);
763                 let mut hmac = Hmac::new(Sha256::new(), &[0x61, 0x6d, 0x6d, 0x61, 0x67]); // ammag
764                 hmac.input(&shared_secret[..]);
765                 let mut res = [0; 32];
766                 hmac.raw_result(&mut res);
767                 res
768         }
769
770         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
771         #[inline]
772         fn construct_onion_keys_callback<T: secp256k1::Signing, FType: FnMut(SharedSecret, [u8; 32], PublicKey, &RouteHop)> (secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey, mut callback: FType) -> Result<(), secp256k1::Error> {
773                 let mut blinded_priv = session_priv.clone();
774                 let mut blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
775
776                 for hop in route.hops.iter() {
777                         let shared_secret = SharedSecret::new(secp_ctx, &hop.pubkey, &blinded_priv);
778
779                         let mut sha = Sha256::new();
780                         sha.input(&blinded_pub.serialize()[..]);
781                         sha.input(&shared_secret[..]);
782                         let mut blinding_factor = [0u8; 32];
783                         sha.result(&mut blinding_factor);
784
785                         let ephemeral_pubkey = blinded_pub;
786
787                         blinded_priv.mul_assign(secp_ctx, &SecretKey::from_slice(secp_ctx, &blinding_factor)?)?;
788                         blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
789
790                         callback(shared_secret, blinding_factor, ephemeral_pubkey, hop);
791                 }
792
793                 Ok(())
794         }
795
796         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
797         fn construct_onion_keys<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey) -> Result<Vec<OnionKeys>, secp256k1::Error> {
798                 let mut res = Vec::with_capacity(route.hops.len());
799
800                 Self::construct_onion_keys_callback(secp_ctx, route, session_priv, |shared_secret, _blinding_factor, ephemeral_pubkey, _| {
801                         let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret[..]);
802
803                         res.push(OnionKeys {
804                                 #[cfg(test)]
805                                 shared_secret,
806                                 #[cfg(test)]
807                                 blinding_factor: _blinding_factor,
808                                 ephemeral_pubkey,
809                                 rho,
810                                 mu,
811                         });
812                 })?;
813
814                 Ok(res)
815         }
816
817         /// returns the hop data, as well as the first-hop value_msat and CLTV value we should send.
818         fn build_onion_payloads(route: &Route, starting_htlc_offset: u32) -> Result<(Vec<msgs::OnionHopData>, u64, u32), APIError> {
819                 let mut cur_value_msat = 0u64;
820                 let mut cur_cltv = starting_htlc_offset;
821                 let mut last_short_channel_id = 0;
822                 let mut res: Vec<msgs::OnionHopData> = Vec::with_capacity(route.hops.len());
823                 internal_traits::test_no_dealloc::<msgs::OnionHopData>(None);
824                 unsafe { res.set_len(route.hops.len()); }
825
826                 for (idx, hop) in route.hops.iter().enumerate().rev() {
827                         // First hop gets special values so that it can check, on receipt, that everything is
828                         // exactly as it should be (and the next hop isn't trying to probe to find out if we're
829                         // the intended recipient).
830                         let value_msat = if cur_value_msat == 0 { hop.fee_msat } else { cur_value_msat };
831                         let cltv = if cur_cltv == starting_htlc_offset { hop.cltv_expiry_delta + starting_htlc_offset } else { cur_cltv };
832                         res[idx] = msgs::OnionHopData {
833                                 realm: 0,
834                                 data: msgs::OnionRealm0HopData {
835                                         short_channel_id: last_short_channel_id,
836                                         amt_to_forward: value_msat,
837                                         outgoing_cltv_value: cltv,
838                                 },
839                                 hmac: [0; 32],
840                         };
841                         cur_value_msat += hop.fee_msat;
842                         if cur_value_msat >= 21000000 * 100000000 * 1000 {
843                                 return Err(APIError::RouteError{err: "Channel fees overflowed?!"});
844                         }
845                         cur_cltv += hop.cltv_expiry_delta as u32;
846                         if cur_cltv >= 500000000 {
847                                 return Err(APIError::RouteError{err: "Channel CLTV overflowed?!"});
848                         }
849                         last_short_channel_id = hop.short_channel_id;
850                 }
851                 Ok((res, cur_value_msat, cur_cltv))
852         }
853
854         #[inline]
855         fn shift_arr_right(arr: &mut [u8; 20*65]) {
856                 unsafe {
857                         ptr::copy(arr[0..].as_ptr(), arr[65..].as_mut_ptr(), 19*65);
858                 }
859                 for i in 0..65 {
860                         arr[i] = 0;
861                 }
862         }
863
864         #[inline]
865         fn xor_bufs(dst: &mut[u8], src: &[u8]) {
866                 assert_eq!(dst.len(), src.len());
867
868                 for i in 0..dst.len() {
869                         dst[i] ^= src[i];
870                 }
871         }
872
873         const ZERO:[u8; 21*65] = [0; 21*65];
874         fn construct_onion_packet(mut payloads: Vec<msgs::OnionHopData>, onion_keys: Vec<OnionKeys>, associated_data: &PaymentHash) -> msgs::OnionPacket {
875                 let mut buf = Vec::with_capacity(21*65);
876                 buf.resize(21*65, 0);
877
878                 let filler = {
879                         let iters = payloads.len() - 1;
880                         let end_len = iters * 65;
881                         let mut res = Vec::with_capacity(end_len);
882                         res.resize(end_len, 0);
883
884                         for (i, keys) in onion_keys.iter().enumerate() {
885                                 if i == payloads.len() - 1 { continue; }
886                                 let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
887                                 chacha.process(&ChannelManager::ZERO, &mut buf); // We don't have a seek function :(
888                                 ChannelManager::xor_bufs(&mut res[0..(i + 1)*65], &buf[(20 - i)*65..21*65]);
889                         }
890                         res
891                 };
892
893                 let mut packet_data = [0; 20*65];
894                 let mut hmac_res = [0; 32];
895
896                 for (i, (payload, keys)) in payloads.iter_mut().zip(onion_keys.iter()).rev().enumerate() {
897                         ChannelManager::shift_arr_right(&mut packet_data);
898                         payload.hmac = hmac_res;
899                         packet_data[0..65].copy_from_slice(&payload.encode()[..]);
900
901                         let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
902                         chacha.process(&packet_data, &mut buf[0..20*65]);
903                         packet_data[..].copy_from_slice(&buf[0..20*65]);
904
905                         if i == 0 {
906                                 packet_data[20*65 - filler.len()..20*65].copy_from_slice(&filler[..]);
907                         }
908
909                         let mut hmac = Hmac::new(Sha256::new(), &keys.mu);
910                         hmac.input(&packet_data);
911                         hmac.input(&associated_data.0[..]);
912                         hmac.raw_result(&mut hmac_res);
913                 }
914
915                 msgs::OnionPacket{
916                         version: 0,
917                         public_key: Ok(onion_keys.first().unwrap().ephemeral_pubkey),
918                         hop_data: packet_data,
919                         hmac: hmac_res,
920                 }
921         }
922
923         /// Encrypts a failure packet. raw_packet can either be a
924         /// msgs::DecodedOnionErrorPacket.encode() result or a msgs::OnionErrorPacket.data element.
925         fn encrypt_failure_packet(shared_secret: &[u8], raw_packet: &[u8]) -> msgs::OnionErrorPacket {
926                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
927
928                 let mut packet_crypted = Vec::with_capacity(raw_packet.len());
929                 packet_crypted.resize(raw_packet.len(), 0);
930                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
931                 chacha.process(&raw_packet, &mut packet_crypted[..]);
932                 msgs::OnionErrorPacket {
933                         data: packet_crypted,
934                 }
935         }
936
937         fn build_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::DecodedOnionErrorPacket {
938                 assert_eq!(shared_secret.len(), 32);
939                 assert!(failure_data.len() <= 256 - 2);
940
941                 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
942
943                 let failuremsg = {
944                         let mut res = Vec::with_capacity(2 + failure_data.len());
945                         res.push(((failure_type >> 8) & 0xff) as u8);
946                         res.push(((failure_type >> 0) & 0xff) as u8);
947                         res.extend_from_slice(&failure_data[..]);
948                         res
949                 };
950                 let pad = {
951                         let mut res = Vec::with_capacity(256 - 2 - failure_data.len());
952                         res.resize(256 - 2 - failure_data.len(), 0);
953                         res
954                 };
955                 let mut packet = msgs::DecodedOnionErrorPacket {
956                         hmac: [0; 32],
957                         failuremsg: failuremsg,
958                         pad: pad,
959                 };
960
961                 let mut hmac = Hmac::new(Sha256::new(), &um);
962                 hmac.input(&packet.encode()[32..]);
963                 hmac.raw_result(&mut packet.hmac);
964
965                 packet
966         }
967
968         #[inline]
969         fn build_first_hop_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::OnionErrorPacket {
970                 let failure_packet = ChannelManager::build_failure_packet(shared_secret, failure_type, failure_data);
971                 ChannelManager::encrypt_failure_packet(shared_secret, &failure_packet.encode()[..])
972         }
973
974         fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder>) {
975                 macro_rules! return_malformed_err {
976                         ($msg: expr, $err_code: expr) => {
977                                 {
978                                         log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
979                                         let mut sha256_of_onion = [0; 32];
980                                         let mut sha = Sha256::new();
981                                         sha.input(&msg.onion_routing_packet.hop_data);
982                                         sha.result(&mut sha256_of_onion);
983                                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
984                                                 channel_id: msg.channel_id,
985                                                 htlc_id: msg.htlc_id,
986                                                 sha256_of_onion,
987                                                 failure_code: $err_code,
988                                         })), self.channel_state.lock().unwrap());
989                                 }
990                         }
991                 }
992
993                 if let Err(_) = msg.onion_routing_packet.public_key {
994                         return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
995                 }
996
997                 let shared_secret = {
998                         let mut arr = [0; 32];
999                         arr.copy_from_slice(&SharedSecret::new(&self.secp_ctx, &msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key)[..]);
1000                         arr
1001                 };
1002                 let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
1003
1004                 if msg.onion_routing_packet.version != 0 {
1005                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
1006                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
1007                         //the hash doesn't really serve any purpuse - in the case of hashing all data, the
1008                         //receiving node would have to brute force to figure out which version was put in the
1009                         //packet by the node that send us the message, in the case of hashing the hop_data, the
1010                         //node knows the HMAC matched, so they already know what is there...
1011                         return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
1012                 }
1013
1014                 let mut hmac = Hmac::new(Sha256::new(), &mu);
1015                 hmac.input(&msg.onion_routing_packet.hop_data);
1016                 hmac.input(&msg.payment_hash.0[..]);
1017                 if hmac.result() != MacResult::new(&msg.onion_routing_packet.hmac) {
1018                         return_malformed_err!("HMAC Check failed", 0x8000 | 0x4000 | 5);
1019                 }
1020
1021                 let mut channel_state = None;
1022                 macro_rules! return_err {
1023                         ($msg: expr, $err_code: expr, $data: expr) => {
1024                                 {
1025                                         log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
1026                                         if channel_state.is_none() {
1027                                                 channel_state = Some(self.channel_state.lock().unwrap());
1028                                         }
1029                                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
1030                                                 channel_id: msg.channel_id,
1031                                                 htlc_id: msg.htlc_id,
1032                                                 reason: ChannelManager::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
1033                                         })), channel_state.unwrap());
1034                                 }
1035                         }
1036                 }
1037
1038                 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
1039                 let next_hop_data = {
1040                         let mut decoded = [0; 65];
1041                         chacha.process(&msg.onion_routing_packet.hop_data[0..65], &mut decoded);
1042                         match msgs::OnionHopData::read(&mut Cursor::new(&decoded[..])) {
1043                                 Err(err) => {
1044                                         let error_code = match err {
1045                                                 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
1046                                                 _ => 0x2000 | 2, // Should never happen
1047                                         };
1048                                         return_err!("Unable to decode our hop data", error_code, &[0;0]);
1049                                 },
1050                                 Ok(msg) => msg
1051                         }
1052                 };
1053
1054                 let pending_forward_info = if next_hop_data.hmac == [0; 32] {
1055                                 // OUR PAYMENT!
1056                                 // final_expiry_too_soon
1057                                 if (msg.cltv_expiry as u64) < self.latest_block_height.load(Ordering::Acquire) as u64 + (CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS) as u64 {
1058                                         return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
1059                                 }
1060                                 // final_incorrect_htlc_amount
1061                                 if next_hop_data.data.amt_to_forward > msg.amount_msat {
1062                                         return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
1063                                 }
1064                                 // final_incorrect_cltv_expiry
1065                                 if next_hop_data.data.outgoing_cltv_value != msg.cltv_expiry {
1066                                         return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
1067                                 }
1068
1069                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
1070                                 // message, however that would leak that we are the recipient of this payment, so
1071                                 // instead we stay symmetric with the forwarding case, only responding (after a
1072                                 // delay) once they've send us a commitment_signed!
1073
1074                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1075                                         onion_packet: None,
1076                                         payment_hash: msg.payment_hash.clone(),
1077                                         short_channel_id: 0,
1078                                         incoming_shared_secret: shared_secret,
1079                                         amt_to_forward: next_hop_data.data.amt_to_forward,
1080                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1081                                 })
1082                         } else {
1083                                 let mut new_packet_data = [0; 20*65];
1084                                 chacha.process(&msg.onion_routing_packet.hop_data[65..], &mut new_packet_data[0..19*65]);
1085                                 chacha.process(&ChannelManager::ZERO[0..65], &mut new_packet_data[19*65..]);
1086
1087                                 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
1088
1089                                 let blinding_factor = {
1090                                         let mut sha = Sha256::new();
1091                                         sha.input(&new_pubkey.serialize()[..]);
1092                                         sha.input(&shared_secret);
1093                                         let mut res = [0u8; 32];
1094                                         sha.result(&mut res);
1095                                         SecretKey::from_slice(&self.secp_ctx, &res).expect("SHA-256 is broken?")
1096                                 };
1097
1098                                 let public_key = if let Err(e) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor) {
1099                                         Err(e)
1100                                 } else { Ok(new_pubkey) };
1101
1102                                 let outgoing_packet = msgs::OnionPacket {
1103                                         version: 0,
1104                                         public_key,
1105                                         hop_data: new_packet_data,
1106                                         hmac: next_hop_data.hmac.clone(),
1107                                 };
1108
1109                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1110                                         onion_packet: Some(outgoing_packet),
1111                                         payment_hash: msg.payment_hash.clone(),
1112                                         short_channel_id: next_hop_data.data.short_channel_id,
1113                                         incoming_shared_secret: shared_secret,
1114                                         amt_to_forward: next_hop_data.data.amt_to_forward,
1115                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1116                                 })
1117                         };
1118
1119                 channel_state = Some(self.channel_state.lock().unwrap());
1120                 if let &PendingHTLCStatus::Forward(PendingForwardHTLCInfo { ref onion_packet, ref short_channel_id, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
1121                         if onion_packet.is_some() { // If short_channel_id is 0 here, we'll reject them in the body here
1122                                 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
1123                                 let forwarding_id = match id_option {
1124                                         None => { // unknown_next_peer
1125                                                 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
1126                                         },
1127                                         Some(id) => id.clone(),
1128                                 };
1129                                 if let Some((err, code, chan_update)) = loop {
1130                                         let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
1131
1132                                         // Note that we could technically not return an error yet here and just hope
1133                                         // that the connection is reestablished or monitor updated by the time we get
1134                                         // around to doing the actual forward, but better to fail early if we can and
1135                                         // hopefully an attacker trying to path-trace payments cannot make this occur
1136                                         // on a small/per-node/per-channel scale.
1137                                         if !chan.is_live() { // channel_disabled
1138                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
1139                                         }
1140                                         if *amt_to_forward < chan.get_their_htlc_minimum_msat() { // amount_below_minimum
1141                                                 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
1142                                         }
1143                                         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) });
1144                                         if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
1145                                                 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())));
1146                                         }
1147                                         if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 { // incorrect_cltv_expiry
1148                                                 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())));
1149                                         }
1150                                         let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1151                                         // We want to have at least HTLC_FAIL_TIMEOUT_BLOCKS to fail prior to going on chain CLAIM_BUFFER blocks before expiration
1152                                         if msg.cltv_expiry <= cur_height + CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS as u32 { // expiry_too_soon
1153                                                 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1154                                         }
1155                                         if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
1156                                                 break Some(("CLTV expiry is too far in the future", 21, None));
1157                                         }
1158                                         break None;
1159                                 }
1160                                 {
1161                                         let mut res = Vec::with_capacity(8 + 128);
1162                                         if let Some(chan_update) = chan_update {
1163                                                 if code == 0x1000 | 11 || code == 0x1000 | 12 {
1164                                                         res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
1165                                                 }
1166                                                 else if code == 0x1000 | 13 {
1167                                                         res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
1168                                                 }
1169                                                 else if code == 0x1000 | 20 {
1170                                                         res.extend_from_slice(&byte_utils::be16_to_array(chan_update.contents.flags));
1171                                                 }
1172                                                 res.extend_from_slice(&chan_update.encode_with_len()[..]);
1173                                         }
1174                                         return_err!(err, code, &res[..]);
1175                                 }
1176                         }
1177                 }
1178
1179                 (pending_forward_info, channel_state.unwrap())
1180         }
1181
1182         /// only fails if the channel does not yet have an assigned short_id
1183         /// May be called with channel_state already locked!
1184         fn get_channel_update(&self, chan: &Channel) -> Result<msgs::ChannelUpdate, HandleError> {
1185                 let short_channel_id = match chan.get_short_channel_id() {
1186                         None => return Err(HandleError{err: "Channel not yet established", action: None}),
1187                         Some(id) => id,
1188                 };
1189
1190                 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_their_node_id().serialize()[..];
1191
1192                 let unsigned = msgs::UnsignedChannelUpdate {
1193                         chain_hash: self.genesis_hash,
1194                         short_channel_id: short_channel_id,
1195                         timestamp: chan.get_channel_update_count(),
1196                         flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
1197                         cltv_expiry_delta: CLTV_EXPIRY_DELTA,
1198                         htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
1199                         fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
1200                         fee_proportional_millionths: chan.get_fee_proportional_millionths(),
1201                         excess_data: Vec::new(),
1202                 };
1203
1204                 let msg_hash = Sha256dHash::from_data(&unsigned.encode()[..]);
1205                 let sig = self.secp_ctx.sign(&Message::from_slice(&msg_hash[..]).unwrap(), &self.our_network_key);
1206
1207                 Ok(msgs::ChannelUpdate {
1208                         signature: sig,
1209                         contents: unsigned
1210                 })
1211         }
1212
1213         /// Sends a payment along a given route.
1214         ///
1215         /// Value parameters are provided via the last hop in route, see documentation for RouteHop
1216         /// fields for more info.
1217         ///
1218         /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
1219         /// payment), we don't do anything to stop you! We always try to ensure that if the provided
1220         /// next hop knows the preimage to payment_hash they can claim an additional amount as
1221         /// specified in the last hop in the route! Thus, you should probably do your own
1222         /// payment_preimage tracking (which you should already be doing as they represent "proof of
1223         /// payment") and prevent double-sends yourself.
1224         ///
1225         /// May generate a SendHTLCs message event on success, which should be relayed.
1226         ///
1227         /// Raises APIError::RoutError when invalid route or forward parameter
1228         /// (cltv_delta, fee, node public key) is specified.
1229         /// Raises APIError::ChannelUnavailable if the next-hop channel is not available for updates
1230         /// (including due to previous monitor update failure or new permanent monitor update failure).
1231         /// Raised APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
1232         /// relevant updates.
1233         ///
1234         /// In case of APIError::RouteError/APIError::ChannelUnavailable, the payment send has failed
1235         /// and you may wish to retry via a different route immediately.
1236         /// In case of APIError::MonitorUpdateFailed, the commitment update has been irrevocably
1237         /// committed on our end and we're just waiting for a monitor update to send it. Do NOT retry
1238         /// the payment via a different route unless you intend to pay twice!
1239         pub fn send_payment(&self, route: Route, payment_hash: PaymentHash) -> Result<(), APIError> {
1240                 if route.hops.len() < 1 || route.hops.len() > 20 {
1241                         return Err(APIError::RouteError{err: "Route didn't go anywhere/had bogus size"});
1242                 }
1243                 let our_node_id = self.get_our_node_id();
1244                 for (idx, hop) in route.hops.iter().enumerate() {
1245                         if idx != route.hops.len() - 1 && hop.pubkey == our_node_id {
1246                                 return Err(APIError::RouteError{err: "Route went through us but wasn't a simple rebalance loop to us"});
1247                         }
1248                 }
1249
1250                 let session_priv = self.keys_manager.get_session_key();
1251
1252                 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1253
1254                 let onion_keys = secp_call!(ChannelManager::construct_onion_keys(&self.secp_ctx, &route, &session_priv),
1255                                 APIError::RouteError{err: "Pubkey along hop was maliciously selected"});
1256                 let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height)?;
1257                 let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
1258
1259                 let _ = self.total_consistency_lock.read().unwrap();
1260
1261                 let err: Result<(), _> = loop {
1262                         let mut channel_lock = self.channel_state.lock().unwrap();
1263
1264                         let id = match channel_lock.short_to_id.get(&route.hops.first().unwrap().short_channel_id) {
1265                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!"}),
1266                                 Some(id) => id.clone(),
1267                         };
1268
1269                         let channel_state = channel_lock.borrow_parts();
1270                         if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) {
1271                                 match {
1272                                         if chan.get().get_their_node_id() != route.hops.first().unwrap().pubkey {
1273                                                 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1274                                         }
1275                                         if !chan.get().is_live() {
1276                                                 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!"});
1277                                         }
1278                                         break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1279                                                 route: route.clone(),
1280                                                 session_priv: session_priv.clone(),
1281                                                 first_hop_htlc_msat: htlc_msat,
1282                                         }, onion_packet), channel_state, chan)
1283                                 } {
1284                                         Some((update_add, commitment_signed, chan_monitor)) => {
1285                                                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1286                                                         maybe_break_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst);
1287                                                         // Note that MonitorUpdateFailed here indicates (per function docs)
1288                                                         // that we will resent the commitment update once we unfree monitor
1289                                                         // updating, so we have to take special care that we don't return
1290                                                         // something else in case we will resend later!
1291                                                         return Err(APIError::MonitorUpdateFailed);
1292                                                 }
1293
1294                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1295                                                         node_id: route.hops.first().unwrap().pubkey,
1296                                                         updates: msgs::CommitmentUpdate {
1297                                                                 update_add_htlcs: vec![update_add],
1298                                                                 update_fulfill_htlcs: Vec::new(),
1299                                                                 update_fail_htlcs: Vec::new(),
1300                                                                 update_fail_malformed_htlcs: Vec::new(),
1301                                                                 update_fee: None,
1302                                                                 commitment_signed,
1303                                                         },
1304                                                 });
1305                                         },
1306                                         None => {},
1307                                 }
1308                         } else { unreachable!(); }
1309                         return Ok(());
1310                 };
1311
1312                 match handle_error!(self, err, route.hops.first().unwrap().pubkey) {
1313                         Ok(_) => unreachable!(),
1314                         Err(e) => {
1315                                 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
1316                                 } else {
1317                                         log_error!(self, "Got bad keys: {}!", e.err);
1318                                         let mut channel_state = self.channel_state.lock().unwrap();
1319                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1320                                                 node_id: route.hops.first().unwrap().pubkey,
1321                                                 action: e.action,
1322                                         });
1323                                 }
1324                                 Err(APIError::ChannelUnavailable { err: e.err })
1325                         },
1326                 }
1327         }
1328
1329         /// Call this upon creation of a funding transaction for the given channel.
1330         ///
1331         /// Note that ALL inputs in the transaction pointed to by funding_txo MUST spend SegWit outputs
1332         /// or your counterparty can steal your funds!
1333         ///
1334         /// Panics if a funding transaction has already been provided for this channel.
1335         ///
1336         /// May panic if the funding_txo is duplicative with some other channel (note that this should
1337         /// be trivially prevented by using unique funding transaction keys per-channel).
1338         pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1339                 let _ = self.total_consistency_lock.read().unwrap();
1340
1341                 let (chan, msg, chan_monitor) = {
1342                         let (res, chan) = {
1343                                 let mut channel_state = self.channel_state.lock().unwrap();
1344                                 match channel_state.by_id.remove(temporary_channel_id) {
1345                                         Some(mut chan) => {
1346                                                 (chan.get_outbound_funding_created(funding_txo)
1347                                                         .map_err(|e| if let ChannelError::Close(msg) = e {
1348                                                                 MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.force_shutdown(), None)
1349                                                         } else { unreachable!(); })
1350                                                 , chan)
1351                                         },
1352                                         None => return
1353                                 }
1354                         };
1355                         match handle_error!(self, res, chan.get_their_node_id()) {
1356                                 Ok(funding_msg) => {
1357                                         (chan, funding_msg.0, funding_msg.1)
1358                                 },
1359                                 Err(e) => {
1360                                         log_error!(self, "Got bad signatures: {}!", e.err);
1361                                         let mut channel_state = self.channel_state.lock().unwrap();
1362                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1363                                                 node_id: chan.get_their_node_id(),
1364                                                 action: e.action,
1365                                         });
1366                                         return;
1367                                 },
1368                         }
1369                 };
1370                 // Because we have exclusive ownership of the channel here we can release the channel_state
1371                 // lock before add_update_monitor
1372                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1373                         unimplemented!();
1374                 }
1375
1376                 let mut channel_state = self.channel_state.lock().unwrap();
1377                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
1378                         node_id: chan.get_their_node_id(),
1379                         msg: msg,
1380                 });
1381                 match channel_state.by_id.entry(chan.channel_id()) {
1382                         hash_map::Entry::Occupied(_) => {
1383                                 panic!("Generated duplicate funding txid?");
1384                         },
1385                         hash_map::Entry::Vacant(e) => {
1386                                 e.insert(chan);
1387                         }
1388                 }
1389         }
1390
1391         fn get_announcement_sigs(&self, chan: &Channel) -> Option<msgs::AnnouncementSignatures> {
1392                 if !chan.should_announce() { return None }
1393
1394                 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1395                         Ok(res) => res,
1396                         Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1397                 };
1398                 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
1399                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1400
1401                 Some(msgs::AnnouncementSignatures {
1402                         channel_id: chan.channel_id(),
1403                         short_channel_id: chan.get_short_channel_id().unwrap(),
1404                         node_signature: our_node_sig,
1405                         bitcoin_signature: our_bitcoin_sig,
1406                 })
1407         }
1408
1409         /// Processes HTLCs which are pending waiting on random forward delay.
1410         ///
1411         /// Should only really ever be called in response to an PendingHTLCsForwardable event.
1412         /// Will likely generate further events.
1413         pub fn process_pending_htlc_forwards(&self) {
1414                 let _ = self.total_consistency_lock.read().unwrap();
1415
1416                 let mut new_events = Vec::new();
1417                 let mut failed_forwards = Vec::new();
1418                 {
1419                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1420                         let channel_state = channel_state_lock.borrow_parts();
1421
1422                         if cfg!(not(feature = "fuzztarget")) && Instant::now() < *channel_state.next_forward {
1423                                 return;
1424                         }
1425
1426                         for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1427                                 if short_chan_id != 0 {
1428                                         let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1429                                                 Some(chan_id) => chan_id.clone(),
1430                                                 None => {
1431                                                         failed_forwards.reserve(pending_forwards.len());
1432                                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1433                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1434                                                                         short_channel_id: prev_short_channel_id,
1435                                                                         htlc_id: prev_htlc_id,
1436                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1437                                                                 });
1438                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
1439                                                         }
1440                                                         continue;
1441                                                 }
1442                                         };
1443                                         let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();
1444
1445                                         let mut add_htlc_msgs = Vec::new();
1446                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1447                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1448                                                         short_channel_id: prev_short_channel_id,
1449                                                         htlc_id: prev_htlc_id,
1450                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1451                                                 });
1452                                                 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()) {
1453                                                         Err(_e) => {
1454                                                                 let chan_update = self.get_channel_update(forward_chan).unwrap();
1455                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x1000 | 7, Some(chan_update)));
1456                                                                 continue;
1457                                                         },
1458                                                         Ok(update_add) => {
1459                                                                 match update_add {
1460                                                                         Some(msg) => { add_htlc_msgs.push(msg); },
1461                                                                         None => {
1462                                                                                 // Nothing to do here...we're waiting on a remote
1463                                                                                 // revoke_and_ack before we can add anymore HTLCs. The Channel
1464                                                                                 // will automatically handle building the update_add_htlc and
1465                                                                                 // commitment_signed messages when we can.
1466                                                                                 // TODO: Do some kind of timer to set the channel as !is_live()
1467                                                                                 // as we don't really want others relying on us relaying through
1468                                                                                 // this channel currently :/.
1469                                                                         }
1470                                                                 }
1471                                                         }
1472                                                 }
1473                                         }
1474
1475                                         if !add_htlc_msgs.is_empty() {
1476                                                 let (commitment_msg, monitor) = match forward_chan.send_commitment() {
1477                                                         Ok(res) => res,
1478                                                         Err(e) => {
1479                                                                 if let ChannelError::Ignore(_) = e {
1480                                                                         panic!("Stated return value requirements in send_commitment() were not met");
1481                                                                 }
1482                                                                 //TODO: Handle...this is bad!
1483                                                                 continue;
1484                                                         },
1485                                                 };
1486                                                 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
1487                                                         unimplemented!();
1488                                                 }
1489                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1490                                                         node_id: forward_chan.get_their_node_id(),
1491                                                         updates: msgs::CommitmentUpdate {
1492                                                                 update_add_htlcs: add_htlc_msgs,
1493                                                                 update_fulfill_htlcs: Vec::new(),
1494                                                                 update_fail_htlcs: Vec::new(),
1495                                                                 update_fail_malformed_htlcs: Vec::new(),
1496                                                                 update_fee: None,
1497                                                                 commitment_signed: commitment_msg,
1498                                                         },
1499                                                 });
1500                                         }
1501                                 } else {
1502                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1503                                                 let prev_hop_data = HTLCPreviousHopData {
1504                                                         short_channel_id: prev_short_channel_id,
1505                                                         htlc_id: prev_htlc_id,
1506                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1507                                                 };
1508                                                 match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
1509                                                         hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(prev_hop_data),
1510                                                         hash_map::Entry::Vacant(entry) => { entry.insert(vec![prev_hop_data]); },
1511                                                 };
1512                                                 new_events.push(events::Event::PaymentReceived {
1513                                                         payment_hash: forward_info.payment_hash,
1514                                                         amt: forward_info.amt_to_forward,
1515                                                 });
1516                                         }
1517                                 }
1518                         }
1519                 }
1520
1521                 for (htlc_source, payment_hash, failure_code, update) in failed_forwards.drain(..) {
1522                         match update {
1523                                 None => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code, data: Vec::new() }),
1524                                 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() }),
1525                         };
1526                 }
1527
1528                 if new_events.is_empty() { return }
1529                 let mut events = self.pending_events.lock().unwrap();
1530                 events.append(&mut new_events);
1531         }
1532
1533         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect after a PaymentReceived event.
1534         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash, reason: PaymentFailReason) -> bool {
1535                 let _ = self.total_consistency_lock.read().unwrap();
1536
1537                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1538                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(payment_hash);
1539                 if let Some(mut sources) = removed_source {
1540                         for htlc_with_hash in sources.drain(..) {
1541                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1542                                 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() });
1543                         }
1544                         true
1545                 } else { false }
1546         }
1547
1548         /// Fails an HTLC backwards to the sender of it to us.
1549         /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
1550         /// There are several callsites that do stupid things like loop over a list of payment_hashes
1551         /// to fail and take the channel_state lock for each iteration (as we take ownership and may
1552         /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
1553         /// still-available channels.
1554         fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
1555                 match source {
1556                         HTLCSource::OutboundRoute { ref route, .. } => {
1557                                 log_trace!(self, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1558                                 mem::drop(channel_state_lock);
1559                                 match &onion_error {
1560                                         &HTLCFailReason::ErrorPacket { ref err } => {
1561 #[cfg(test)]
1562                                                 let (channel_update, payment_retryable, onion_error_code) = self.process_onion_failure(&source, err.data.clone());
1563 #[cfg(not(test))]
1564                                                 let (channel_update, payment_retryable, _) = self.process_onion_failure(&source, err.data.clone());
1565                                                 // TODO: If we decided to blame ourselves (or one of our channels) in
1566                                                 // process_onion_failure we should close that channel as it implies our
1567                                                 // next-hop is needlessly blaming us!
1568                                                 if let Some(update) = channel_update {
1569                                                         self.channel_state.lock().unwrap().pending_msg_events.push(
1570                                                                 events::MessageSendEvent::PaymentFailureNetworkUpdate {
1571                                                                         update,
1572                                                                 }
1573                                                         );
1574                                                 }
1575                                                 self.pending_events.lock().unwrap().push(
1576                                                         events::Event::PaymentFailed {
1577                                                                 payment_hash: payment_hash.clone(),
1578                                                                 rejected_by_dest: !payment_retryable,
1579 #[cfg(test)]
1580                                                                 error_code: onion_error_code
1581                                                         }
1582                                                 );
1583                                         },
1584                                         &HTLCFailReason::Reason {
1585 #[cfg(test)]
1586                                                         ref failure_code,
1587                                                         .. } => {
1588                                                 // we get a fail_malformed_htlc from the first hop
1589                                                 // TODO: We'd like to generate a PaymentFailureNetworkUpdate for temporary
1590                                                 // failures here, but that would be insufficient as Router::get_route
1591                                                 // generally ignores its view of our own channels as we provide them via
1592                                                 // ChannelDetails.
1593                                                 // TODO: For non-temporary failures, we really should be closing the
1594                                                 // channel here as we apparently can't relay through them anyway.
1595                                                 self.pending_events.lock().unwrap().push(
1596                                                         events::Event::PaymentFailed {
1597                                                                 payment_hash: payment_hash.clone(),
1598                                                                 rejected_by_dest: route.hops.len() == 1,
1599 #[cfg(test)]
1600                                                                 error_code: Some(*failure_code),
1601                                                         }
1602                                                 );
1603                                         }
1604                                 }
1605                         },
1606                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
1607                                 let err_packet = match onion_error {
1608                                         HTLCFailReason::Reason { failure_code, data } => {
1609                                                 log_trace!(self, "Failing HTLC with payment_hash {} backwards from us with code {}", log_bytes!(payment_hash.0), failure_code);
1610                                                 let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1611                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1612                                         },
1613                                         HTLCFailReason::ErrorPacket { err } => {
1614                                                 log_trace!(self, "Failing HTLC with payment_hash {} backwards with pre-built ErrorPacket", log_bytes!(payment_hash.0));
1615                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1616                                         }
1617                                 };
1618
1619                                 let channel_state = channel_state_lock.borrow_parts();
1620
1621                                 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1622                                         Some(chan_id) => chan_id.clone(),
1623                                         None => return
1624                                 };
1625
1626                                 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1627                                 match chan.get_update_fail_htlc_and_commit(htlc_id, err_packet) {
1628                                         Ok(Some((msg, commitment_msg, chan_monitor))) => {
1629                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1630                                                         unimplemented!();
1631                                                 }
1632                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1633                                                         node_id: chan.get_their_node_id(),
1634                                                         updates: msgs::CommitmentUpdate {
1635                                                                 update_add_htlcs: Vec::new(),
1636                                                                 update_fulfill_htlcs: Vec::new(),
1637                                                                 update_fail_htlcs: vec![msg],
1638                                                                 update_fail_malformed_htlcs: Vec::new(),
1639                                                                 update_fee: None,
1640                                                                 commitment_signed: commitment_msg,
1641                                                         },
1642                                                 });
1643                                         },
1644                                         Ok(None) => {},
1645                                         Err(_e) => {
1646                                                 //TODO: Do something with e?
1647                                                 return;
1648                                         },
1649                                 }
1650                         },
1651                 }
1652         }
1653
1654         /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1655         /// generating message events for the net layer to claim the payment, if possible. Thus, you
1656         /// should probably kick the net layer to go send messages if this returns true!
1657         ///
1658         /// May panic if called except in response to a PaymentReceived event.
1659         pub fn claim_funds(&self, payment_preimage: PaymentPreimage) -> bool {
1660                 let mut sha = Sha256::new();
1661                 sha.input(&payment_preimage.0[..]);
1662                 let mut payment_hash = PaymentHash([0; 32]);
1663                 sha.result(&mut payment_hash.0[..]);
1664
1665                 let _ = self.total_consistency_lock.read().unwrap();
1666
1667                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1668                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&payment_hash);
1669                 if let Some(mut sources) = removed_source {
1670                         for htlc_with_hash in sources.drain(..) {
1671                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1672                                 self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_preimage);
1673                         }
1674                         true
1675                 } else { false }
1676         }
1677         fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_preimage: PaymentPreimage) {
1678                 match source {
1679                         HTLCSource::OutboundRoute { .. } => {
1680                                 mem::drop(channel_state_lock);
1681                                 let mut pending_events = self.pending_events.lock().unwrap();
1682                                 pending_events.push(events::Event::PaymentSent {
1683                                         payment_preimage
1684                                 });
1685                         },
1686                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, .. }) => {
1687                                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1688                                 let channel_state = channel_state_lock.borrow_parts();
1689
1690                                 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1691                                         Some(chan_id) => chan_id.clone(),
1692                                         None => {
1693                                                 // TODO: There is probably a channel manager somewhere that needs to
1694                                                 // learn the preimage as the channel already hit the chain and that's
1695                                                 // why its missing.
1696                                                 return
1697                                         }
1698                                 };
1699
1700                                 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1701                                 match chan.get_update_fulfill_htlc_and_commit(htlc_id, payment_preimage) {
1702                                         Ok((msgs, monitor_option)) => {
1703                                                 if let Some(chan_monitor) = monitor_option {
1704                                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1705                                                                 unimplemented!();// but def dont push the event...
1706                                                         }
1707                                                 }
1708                                                 if let Some((msg, commitment_signed)) = msgs {
1709                                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1710                                                                 node_id: chan.get_their_node_id(),
1711                                                                 updates: msgs::CommitmentUpdate {
1712                                                                         update_add_htlcs: Vec::new(),
1713                                                                         update_fulfill_htlcs: vec![msg],
1714                                                                         update_fail_htlcs: Vec::new(),
1715                                                                         update_fail_malformed_htlcs: Vec::new(),
1716                                                                         update_fee: None,
1717                                                                         commitment_signed,
1718                                                                 }
1719                                                         });
1720                                                 }
1721                                         },
1722                                         Err(_e) => {
1723                                                 // TODO: There is probably a channel manager somewhere that needs to
1724                                                 // learn the preimage as the channel may be about to hit the chain.
1725                                                 //TODO: Do something with e?
1726                                                 return
1727                                         },
1728                                 }
1729                         },
1730                 }
1731         }
1732
1733         /// Gets the node_id held by this ChannelManager
1734         pub fn get_our_node_id(&self) -> PublicKey {
1735                 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
1736         }
1737
1738         /// Used to restore channels to normal operation after a
1739         /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
1740         /// operation.
1741         pub fn test_restore_channel_monitor(&self) {
1742                 let mut close_results = Vec::new();
1743                 let mut htlc_forwards = Vec::new();
1744                 let mut htlc_failures = Vec::new();
1745                 let _ = self.total_consistency_lock.read().unwrap();
1746
1747                 {
1748                         let mut channel_lock = self.channel_state.lock().unwrap();
1749                         let channel_state = channel_lock.borrow_parts();
1750                         let short_to_id = channel_state.short_to_id;
1751                         let pending_msg_events = channel_state.pending_msg_events;
1752                         channel_state.by_id.retain(|_, channel| {
1753                                 if channel.is_awaiting_monitor_update() {
1754                                         let chan_monitor = channel.channel_monitor();
1755                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1756                                                 match e {
1757                                                         ChannelMonitorUpdateErr::PermanentFailure => {
1758                                                                 // TODO: There may be some pending HTLCs that we intended to fail
1759                                                                 // backwards when a monitor update failed. We should make sure
1760                                                                 // knowledge of those gets moved into the appropriate in-memory
1761                                                                 // ChannelMonitor and they get failed backwards once we get
1762                                                                 // on-chain confirmations.
1763                                                                 // Note I think #198 addresses this, so once its merged a test
1764                                                                 // should be written.
1765                                                                 if let Some(short_id) = channel.get_short_channel_id() {
1766                                                                         short_to_id.remove(&short_id);
1767                                                                 }
1768                                                                 close_results.push(channel.force_shutdown());
1769                                                                 if let Ok(update) = self.get_channel_update(&channel) {
1770                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1771                                                                                 msg: update
1772                                                                         });
1773                                                                 }
1774                                                                 false
1775                                                         },
1776                                                         ChannelMonitorUpdateErr::TemporaryFailure => true,
1777                                                 }
1778                                         } else {
1779                                                 let (raa, commitment_update, order, pending_forwards, mut pending_failures) = channel.monitor_updating_restored();
1780                                                 if !pending_forwards.is_empty() {
1781                                                         htlc_forwards.push((channel.get_short_channel_id().expect("We can't have pending forwards before funding confirmation"), pending_forwards));
1782                                                 }
1783                                                 htlc_failures.append(&mut pending_failures);
1784
1785                                                 macro_rules! handle_cs { () => {
1786                                                         if let Some(update) = commitment_update {
1787                                                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1788                                                                         node_id: channel.get_their_node_id(),
1789                                                                         updates: update,
1790                                                                 });
1791                                                         }
1792                                                 } }
1793                                                 macro_rules! handle_raa { () => {
1794                                                         if let Some(revoke_and_ack) = raa {
1795                                                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
1796                                                                         node_id: channel.get_their_node_id(),
1797                                                                         msg: revoke_and_ack,
1798                                                                 });
1799                                                         }
1800                                                 } }
1801                                                 match order {
1802                                                         RAACommitmentOrder::CommitmentFirst => {
1803                                                                 handle_cs!();
1804                                                                 handle_raa!();
1805                                                         },
1806                                                         RAACommitmentOrder::RevokeAndACKFirst => {
1807                                                                 handle_raa!();
1808                                                                 handle_cs!();
1809                                                         },
1810                                                 }
1811                                                 true
1812                                         }
1813                                 } else { true }
1814                         });
1815                 }
1816
1817                 for failure in htlc_failures.drain(..) {
1818                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
1819                 }
1820                 self.forward_htlcs(&mut htlc_forwards[..]);
1821
1822                 for res in close_results.drain(..) {
1823                         self.finish_force_close_channel(res);
1824                 }
1825         }
1826
1827         fn internal_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
1828                 if msg.chain_hash != self.genesis_hash {
1829                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash", msg.temporary_channel_id.clone()));
1830                 }
1831
1832                 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)
1833                         .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
1834                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1835                 let channel_state = channel_state_lock.borrow_parts();
1836                 match channel_state.by_id.entry(channel.channel_id()) {
1837                         hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!", msg.temporary_channel_id.clone())),
1838                         hash_map::Entry::Vacant(entry) => {
1839                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
1840                                         node_id: their_node_id.clone(),
1841                                         msg: channel.get_accept_channel(),
1842                                 });
1843                                 entry.insert(channel);
1844                         }
1845                 }
1846                 Ok(())
1847         }
1848
1849         fn internal_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
1850                 let (value, output_script, user_id) = {
1851                         let mut channel_lock = self.channel_state.lock().unwrap();
1852                         let channel_state = channel_lock.borrow_parts();
1853                         match channel_state.by_id.entry(msg.temporary_channel_id) {
1854                                 hash_map::Entry::Occupied(mut chan) => {
1855                                         if chan.get().get_their_node_id() != *their_node_id {
1856                                                 //TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
1857                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1858                                         }
1859                                         try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration), channel_state, chan);
1860                                         (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
1861                                 },
1862                                 //TODO: same as above
1863                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1864                         }
1865                 };
1866                 let mut pending_events = self.pending_events.lock().unwrap();
1867                 pending_events.push(events::Event::FundingGenerationReady {
1868                         temporary_channel_id: msg.temporary_channel_id,
1869                         channel_value_satoshis: value,
1870                         output_script: output_script,
1871                         user_channel_id: user_id,
1872                 });
1873                 Ok(())
1874         }
1875
1876         fn internal_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
1877                 let ((funding_msg, monitor_update), chan) = {
1878                         let mut channel_lock = self.channel_state.lock().unwrap();
1879                         let channel_state = channel_lock.borrow_parts();
1880                         match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
1881                                 hash_map::Entry::Occupied(mut chan) => {
1882                                         if chan.get().get_their_node_id() != *their_node_id {
1883                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1884                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1885                                         }
1886                                         (try_chan_entry!(self, chan.get_mut().funding_created(msg), channel_state, chan), chan.remove())
1887                                 },
1888                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1889                         }
1890                 };
1891                 // Because we have exclusive ownership of the channel here we can release the channel_state
1892                 // lock before add_update_monitor
1893                 if let Err(_e) = self.monitor.add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) {
1894                         unimplemented!();
1895                 }
1896                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1897                 let channel_state = channel_state_lock.borrow_parts();
1898                 match channel_state.by_id.entry(funding_msg.channel_id) {
1899                         hash_map::Entry::Occupied(_) => {
1900                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id", funding_msg.channel_id))
1901                         },
1902                         hash_map::Entry::Vacant(e) => {
1903                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
1904                                         node_id: their_node_id.clone(),
1905                                         msg: funding_msg,
1906                                 });
1907                                 e.insert(chan);
1908                         }
1909                 }
1910                 Ok(())
1911         }
1912
1913         fn internal_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
1914                 let (funding_txo, user_id) = {
1915                         let mut channel_lock = self.channel_state.lock().unwrap();
1916                         let channel_state = channel_lock.borrow_parts();
1917                         match channel_state.by_id.entry(msg.channel_id) {
1918                                 hash_map::Entry::Occupied(mut chan) => {
1919                                         if chan.get().get_their_node_id() != *their_node_id {
1920                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1921                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1922                                         }
1923                                         let chan_monitor = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
1924                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1925                                                 unimplemented!();
1926                                         }
1927                                         (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())
1928                                 },
1929                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1930                         }
1931                 };
1932                 let mut pending_events = self.pending_events.lock().unwrap();
1933                 pending_events.push(events::Event::FundingBroadcastSafe {
1934                         funding_txo: funding_txo,
1935                         user_channel_id: user_id,
1936                 });
1937                 Ok(())
1938         }
1939
1940         fn internal_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), MsgHandleErrInternal> {
1941                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1942                 let channel_state = channel_state_lock.borrow_parts();
1943                 match channel_state.by_id.entry(msg.channel_id) {
1944                         hash_map::Entry::Occupied(mut chan) => {
1945                                 if chan.get().get_their_node_id() != *their_node_id {
1946                                         //TODO: here and below MsgHandleErrInternal, #153 case
1947                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1948                                 }
1949                                 try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
1950                                 if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
1951                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
1952                                                 node_id: their_node_id.clone(),
1953                                                 msg: announcement_sigs,
1954                                         });
1955                                 }
1956                                 Ok(())
1957                         },
1958                         hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1959                 }
1960         }
1961
1962         fn internal_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
1963                 let (mut dropped_htlcs, chan_option) = {
1964                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1965                         let channel_state = channel_state_lock.borrow_parts();
1966
1967                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1968                                 hash_map::Entry::Occupied(mut chan_entry) => {
1969                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1970                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1971                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1972                                         }
1973                                         let (shutdown, closing_signed, dropped_htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg), channel_state, chan_entry);
1974                                         if let Some(msg) = shutdown {
1975                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
1976                                                         node_id: their_node_id.clone(),
1977                                                         msg,
1978                                                 });
1979                                         }
1980                                         if let Some(msg) = closing_signed {
1981                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1982                                                         node_id: their_node_id.clone(),
1983                                                         msg,
1984                                                 });
1985                                         }
1986                                         if chan_entry.get().is_shutdown() {
1987                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1988                                                         channel_state.short_to_id.remove(&short_id);
1989                                                 }
1990                                                 (dropped_htlcs, Some(chan_entry.remove_entry().1))
1991                                         } else { (dropped_htlcs, None) }
1992                                 },
1993                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1994                         }
1995                 };
1996                 for htlc_source in dropped_htlcs.drain(..) {
1997                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
1998                 }
1999                 if let Some(chan) = chan_option {
2000                         if let Ok(update) = self.get_channel_update(&chan) {
2001                                 let mut channel_state = self.channel_state.lock().unwrap();
2002                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2003                                         msg: update
2004                                 });
2005                         }
2006                 }
2007                 Ok(())
2008         }
2009
2010         fn internal_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
2011                 let (tx, chan_option) = {
2012                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2013                         let channel_state = channel_state_lock.borrow_parts();
2014                         match channel_state.by_id.entry(msg.channel_id.clone()) {
2015                                 hash_map::Entry::Occupied(mut chan_entry) => {
2016                                         if chan_entry.get().get_their_node_id() != *their_node_id {
2017                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2018                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2019                                         }
2020                                         let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg), channel_state, chan_entry);
2021                                         if let Some(msg) = closing_signed {
2022                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2023                                                         node_id: their_node_id.clone(),
2024                                                         msg,
2025                                                 });
2026                                         }
2027                                         if tx.is_some() {
2028                                                 // We're done with this channel, we've got a signed closing transaction and
2029                                                 // will send the closing_signed back to the remote peer upon return. This
2030                                                 // also implies there are no pending HTLCs left on the channel, so we can
2031                                                 // fully delete it from tracking (the channel monitor is still around to
2032                                                 // watch for old state broadcasts)!
2033                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2034                                                         channel_state.short_to_id.remove(&short_id);
2035                                                 }
2036                                                 (tx, Some(chan_entry.remove_entry().1))
2037                                         } else { (tx, None) }
2038                                 },
2039                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2040                         }
2041                 };
2042                 if let Some(broadcast_tx) = tx {
2043                         self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
2044                 }
2045                 if let Some(chan) = chan_option {
2046                         if let Ok(update) = self.get_channel_update(&chan) {
2047                                 let mut channel_state = self.channel_state.lock().unwrap();
2048                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2049                                         msg: update
2050                                 });
2051                         }
2052                 }
2053                 Ok(())
2054         }
2055
2056         fn internal_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
2057                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
2058                 //determine the state of the payment based on our response/if we forward anything/the time
2059                 //we take to respond. We should take care to avoid allowing such an attack.
2060                 //
2061                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
2062                 //us repeatedly garbled in different ways, and compare our error messages, which are
2063                 //encrypted with the same key. Its not immediately obvious how to usefully exploit that,
2064                 //but we should prevent it anyway.
2065
2066                 let (mut pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
2067                 let channel_state = channel_state_lock.borrow_parts();
2068
2069                 match channel_state.by_id.entry(msg.channel_id) {
2070                         hash_map::Entry::Occupied(mut chan) => {
2071                                 if chan.get().get_their_node_id() != *their_node_id {
2072                                         //TODO: here MsgHandleErrInternal, #153 case
2073                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2074                                 }
2075                                 if !chan.get().is_usable() {
2076                                         // If the update_add is completely bogus, the call will Err and we will close,
2077                                         // but if we've sent a shutdown and they haven't acknowledged it yet, we just
2078                                         // want to reject the new HTLC and fail it backwards instead of forwarding.
2079                                         if let PendingHTLCStatus::Forward(PendingForwardHTLCInfo { incoming_shared_secret, .. }) = pending_forward_info {
2080                                                 let chan_update = self.get_channel_update(chan.get());
2081                                                 pending_forward_info = PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
2082                                                         channel_id: msg.channel_id,
2083                                                         htlc_id: msg.htlc_id,
2084                                                         reason: if let Ok(update) = chan_update {
2085                                                                 // TODO: Note that |20 is defined as "channel FROM the processing
2086                                                                 // node has been disabled" (emphasis mine), which seems to imply
2087                                                                 // that we can't return |20 for an inbound channel being disabled.
2088                                                                 // This probably needs a spec update but should definitely be
2089                                                                 // allowed.
2090                                                                 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x1000|20, &{
2091                                                                         let mut res = Vec::with_capacity(8 + 128);
2092                                                                         res.extend_from_slice(&byte_utils::be16_to_array(update.contents.flags));
2093                                                                         res.extend_from_slice(&update.encode_with_len()[..]);
2094                                                                         res
2095                                                                 }[..])
2096                                                         } else {
2097                                                                 // This can only happen if the channel isn't in the fully-funded
2098                                                                 // state yet, implying our counterparty is trying to route payments
2099                                                                 // over the channel back to themselves (cause no one else should
2100                                                                 // know the short_id is a lightning channel yet). We should have no
2101                                                                 // problem just calling this unknown_next_peer
2102                                                                 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x4000|10, &[])
2103                                                         },
2104                                                 }));
2105                                         }
2106                                 }
2107                                 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info), channel_state, chan);
2108                         },
2109                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2110                 }
2111                 Ok(())
2112         }
2113
2114         fn internal_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
2115                 let mut channel_lock = self.channel_state.lock().unwrap();
2116                 let htlc_source = {
2117                         let channel_state = channel_lock.borrow_parts();
2118                         match channel_state.by_id.entry(msg.channel_id) {
2119                                 hash_map::Entry::Occupied(mut chan) => {
2120                                         if chan.get().get_their_node_id() != *their_node_id {
2121                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2122                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2123                                         }
2124                                         try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), channel_state, chan)
2125                                 },
2126                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2127                         }
2128                 };
2129                 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
2130                 Ok(())
2131         }
2132
2133         // Process failure we got back from upstream on a payment we sent. Returns update and a boolean
2134         // indicating that the payment itself failed
2135         fn process_onion_failure(&self, htlc_source: &HTLCSource, mut packet_decrypted: Vec<u8>) -> (Option<msgs::HTLCFailChannelUpdate>, bool, Option<u16>) {
2136                 if let &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } = htlc_source {
2137
2138                         let mut res = None;
2139                         let mut htlc_msat = *first_hop_htlc_msat;
2140                         let mut error_code_ret = None;
2141                         let mut next_route_hop_ix = 0;
2142                         let mut is_from_final_node = false;
2143
2144                         // Handle packed channel/node updates for passing back for the route handler
2145                         Self::construct_onion_keys_callback(&self.secp_ctx, route, session_priv, |shared_secret, _, _, route_hop| {
2146                                 next_route_hop_ix += 1;
2147                                 if res.is_some() { return; }
2148
2149                                 let amt_to_forward = htlc_msat - route_hop.fee_msat;
2150                                 htlc_msat = amt_to_forward;
2151
2152                                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret[..]);
2153
2154                                 let mut decryption_tmp = Vec::with_capacity(packet_decrypted.len());
2155                                 decryption_tmp.resize(packet_decrypted.len(), 0);
2156                                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
2157                                 chacha.process(&packet_decrypted, &mut decryption_tmp[..]);
2158                                 packet_decrypted = decryption_tmp;
2159
2160                                 is_from_final_node = route.hops.last().unwrap().pubkey == route_hop.pubkey;
2161
2162                                 if let Ok(err_packet) = msgs::DecodedOnionErrorPacket::read(&mut Cursor::new(&packet_decrypted)) {
2163                                         let um = ChannelManager::gen_um_from_shared_secret(&shared_secret[..]);
2164                                         let mut hmac = Hmac::new(Sha256::new(), &um);
2165                                         hmac.input(&err_packet.encode()[32..]);
2166                                         let mut calc_tag = [0u8; 32];
2167                                         hmac.raw_result(&mut calc_tag);
2168
2169                                         if crypto::util::fixed_time_eq(&calc_tag, &err_packet.hmac) {
2170                                                 if let Some(error_code_slice) = err_packet.failuremsg.get(0..2) {
2171                                                         const PERM: u16 = 0x4000;
2172                                                         const NODE: u16 = 0x2000;
2173                                                         const UPDATE: u16 = 0x1000;
2174
2175                                                         let error_code = byte_utils::slice_to_be16(&error_code_slice);
2176                                                         error_code_ret = Some(error_code);
2177
2178                                                         let (debug_field, debug_field_size) = errors::get_onion_debug_field(error_code);
2179
2180                                                         // indicate that payment parameter has failed and no need to
2181                                                         // update Route object
2182                                                         let payment_failed = (match error_code & 0xff {
2183                                                                 15|16|17|18|19 => true,
2184                                                                 _ => false,
2185                                                         } && is_from_final_node) // PERM bit observed below even this error is from the intermediate nodes
2186                                                         || error_code == 21; // Special case error 21 as the Route object is bogus, TODO: Maybe fail the node if the CLTV was reasonable?
2187
2188                                                         let mut fail_channel_update = None;
2189
2190                                                         if error_code & NODE == NODE {
2191                                                                 fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure { node_id: route_hop.pubkey, is_permanent: error_code & PERM == PERM });
2192                                                         }
2193                                                         else if error_code & PERM == PERM {
2194                                                                 fail_channel_update = if payment_failed {None} else {Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
2195                                                                         short_channel_id: route.hops[next_route_hop_ix - if next_route_hop_ix == route.hops.len() { 1 } else { 0 }].short_channel_id,
2196                                                                         is_permanent: true,
2197                                                                 })};
2198                                                         }
2199                                                         else if error_code & UPDATE == UPDATE {
2200                                                                 if let Some(update_len_slice) = err_packet.failuremsg.get(debug_field_size+2..debug_field_size+4) {
2201                                                                         let update_len = byte_utils::slice_to_be16(&update_len_slice) as usize;
2202                                                                         if let Some(update_slice) = err_packet.failuremsg.get(debug_field_size + 4..debug_field_size + 4 + update_len) {
2203                                                                                 if let Ok(chan_update) = msgs::ChannelUpdate::read(&mut Cursor::new(&update_slice)) {
2204                                                                                         // if channel_update should NOT have caused the failure:
2205                                                                                         // MAY treat the channel_update as invalid.
2206                                                                                         let is_chan_update_invalid = match error_code & 0xff {
2207                                                                                                 7 => false,
2208                                                                                                 11 => amt_to_forward > chan_update.contents.htlc_minimum_msat,
2209                                                                                                 12 => {
2210                                                                                                         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) });
2211                                                                                                         new_fee.is_some() && route_hop.fee_msat >= new_fee.unwrap()
2212                                                                                                 }
2213                                                                                                 13 => route_hop.cltv_expiry_delta as u16 >= chan_update.contents.cltv_expiry_delta,
2214                                                                                                 14 => false, // expiry_too_soon; always valid?
2215                                                                                                 20 => chan_update.contents.flags & 2 == 0,
2216                                                                                                 _ => false, // unknown error code; take channel_update as valid
2217                                                                                         };
2218                                                                                         fail_channel_update = if is_chan_update_invalid {
2219                                                                                                 // This probably indicates the node which forwarded
2220                                                                                                 // to the node in question corrupted something.
2221                                                                                                 Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
2222                                                                                                         short_channel_id: route_hop.short_channel_id,
2223                                                                                                         is_permanent: true,
2224                                                                                                 })
2225                                                                                         } else {
2226                                                                                                 Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {
2227                                                                                                         msg: chan_update,
2228                                                                                                 })
2229                                                                                         };
2230                                                                                 }
2231                                                                         }
2232                                                                 }
2233                                                                 if fail_channel_update.is_none() {
2234                                                                         // They provided an UPDATE which was obviously bogus, not worth
2235                                                                         // trying to relay through them anymore.
2236                                                                         fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2237                                                                                 node_id: route_hop.pubkey,
2238                                                                                 is_permanent: true,
2239                                                                         });
2240                                                                 }
2241                                                         } else if !payment_failed {
2242                                                                 // We can't understand their error messages and they failed to
2243                                                                 // forward...they probably can't understand our forwards so its
2244                                                                 // really not worth trying any further.
2245                                                                 fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2246                                                                         node_id: route_hop.pubkey,
2247                                                                         is_permanent: true,
2248                                                                 });
2249                                                         }
2250
2251                                                         // TODO: Here (and a few other places) we assume that BADONION errors
2252                                                         // are always "sourced" from the node previous to the one which failed
2253                                                         // to decode the onion.
2254                                                         res = Some((fail_channel_update, !(error_code & PERM == PERM && is_from_final_node)));
2255
2256                                                         let (description, title) = errors::get_onion_error_description(error_code);
2257                                                         if debug_field_size > 0 && err_packet.failuremsg.len() >= 4 + debug_field_size {
2258                                                                 log_warn!(self, "Onion Error[{}({:#x}) {}({})] {}", title, error_code, debug_field, log_bytes!(&err_packet.failuremsg[4..4+debug_field_size]), description);
2259                                                         }
2260                                                         else {
2261                                                                 log_warn!(self, "Onion Error[{}({:#x})] {}", title, error_code, description);
2262                                                         }
2263                                                 } else {
2264                                                         // Useless packet that we can't use but it passed HMAC, so it
2265                                                         // definitely came from the peer in question
2266                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2267                                                                 node_id: route_hop.pubkey,
2268                                                                 is_permanent: true,
2269                                                         }), !is_from_final_node));
2270                                                 }
2271                                         }
2272                                 }
2273                         }).expect("Route that we sent via spontaneously grew invalid keys in the middle of it?");
2274                         if let Some((channel_update, payment_retryable)) = res {
2275                                 (channel_update, payment_retryable, error_code_ret)
2276                         } else {
2277                                 // only not set either packet unparseable or hmac does not match with any
2278                                 // payment not retryable only when garbage is from the final node
2279                                 (None, !is_from_final_node, None)
2280                         }
2281                 } else { unreachable!(); }
2282         }
2283
2284         fn internal_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
2285                 let mut channel_lock = self.channel_state.lock().unwrap();
2286                 let channel_state = channel_lock.borrow_parts();
2287                 match channel_state.by_id.entry(msg.channel_id) {
2288                         hash_map::Entry::Occupied(mut chan) => {
2289                                 if chan.get().get_their_node_id() != *their_node_id {
2290                                         //TODO: here and below MsgHandleErrInternal, #153 case
2291                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2292                                 }
2293                                 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::ErrorPacket { err: msg.reason.clone() }), channel_state, chan);
2294                         },
2295                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2296                 }
2297                 Ok(())
2298         }
2299
2300         fn internal_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
2301                 let mut channel_lock = self.channel_state.lock().unwrap();
2302                 let channel_state = channel_lock.borrow_parts();
2303                 match channel_state.by_id.entry(msg.channel_id) {
2304                         hash_map::Entry::Occupied(mut chan) => {
2305                                 if chan.get().get_their_node_id() != *their_node_id {
2306                                         //TODO: here and below MsgHandleErrInternal, #153 case
2307                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2308                                 }
2309                                 if (msg.failure_code & 0x8000) == 0 {
2310                                         try_chan_entry!(self, Err(ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set")), channel_state, chan);
2311                                 }
2312                                 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);
2313                                 Ok(())
2314                         },
2315                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2316                 }
2317         }
2318
2319         fn internal_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
2320                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2321                 let channel_state = channel_state_lock.borrow_parts();
2322                 match channel_state.by_id.entry(msg.channel_id) {
2323                         hash_map::Entry::Occupied(mut chan) => {
2324                                 if chan.get().get_their_node_id() != *their_node_id {
2325                                         //TODO: here and below MsgHandleErrInternal, #153 case
2326                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2327                                 }
2328                                 let (revoke_and_ack, commitment_signed, closing_signed, chan_monitor) =
2329                                         try_chan_entry!(self, chan.get_mut().commitment_signed(&msg, &*self.fee_estimator), channel_state, chan);
2330                                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2331                                         return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, commitment_signed.is_some());
2332                                         //TODO: Rebroadcast closing_signed if present on monitor update restoration
2333                                 }
2334                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2335                                         node_id: their_node_id.clone(),
2336                                         msg: revoke_and_ack,
2337                                 });
2338                                 if let Some(msg) = commitment_signed {
2339                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2340                                                 node_id: their_node_id.clone(),
2341                                                 updates: msgs::CommitmentUpdate {
2342                                                         update_add_htlcs: Vec::new(),
2343                                                         update_fulfill_htlcs: Vec::new(),
2344                                                         update_fail_htlcs: Vec::new(),
2345                                                         update_fail_malformed_htlcs: Vec::new(),
2346                                                         update_fee: None,
2347                                                         commitment_signed: msg,
2348                                                 },
2349                                         });
2350                                 }
2351                                 if let Some(msg) = closing_signed {
2352                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2353                                                 node_id: their_node_id.clone(),
2354                                                 msg,
2355                                         });
2356                                 }
2357                                 Ok(())
2358                         },
2359                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2360                 }
2361         }
2362
2363         #[inline]
2364         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64)>)]) {
2365                 for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
2366                         let mut forward_event = None;
2367                         if !pending_forwards.is_empty() {
2368                                 let mut channel_state = self.channel_state.lock().unwrap();
2369                                 if channel_state.forward_htlcs.is_empty() {
2370                                         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));
2371                                         channel_state.next_forward = forward_event.unwrap();
2372                                 }
2373                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2374                                         match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
2375                                                 hash_map::Entry::Occupied(mut entry) => {
2376                                                         entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info });
2377                                                 },
2378                                                 hash_map::Entry::Vacant(entry) => {
2379                                                         entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info }));
2380                                                 }
2381                                         }
2382                                 }
2383                         }
2384                         match forward_event {
2385                                 Some(time) => {
2386                                         let mut pending_events = self.pending_events.lock().unwrap();
2387                                         pending_events.push(events::Event::PendingHTLCsForwardable {
2388                                                 time_forwardable: time
2389                                         });
2390                                 }
2391                                 None => {},
2392                         }
2393                 }
2394         }
2395
2396         fn internal_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
2397                 let (pending_forwards, mut pending_failures, short_channel_id) = {
2398                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2399                         let channel_state = channel_state_lock.borrow_parts();
2400                         match channel_state.by_id.entry(msg.channel_id) {
2401                                 hash_map::Entry::Occupied(mut chan) => {
2402                                         if chan.get().get_their_node_id() != *their_node_id {
2403                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2404                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2405                                         }
2406                                         let (commitment_update, pending_forwards, pending_failures, closing_signed, chan_monitor) =
2407                                                 try_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &*self.fee_estimator), channel_state, chan);
2408                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2409                                                 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, pending_forwards, pending_failures);
2410                                         }
2411                                         if let Some(updates) = commitment_update {
2412                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2413                                                         node_id: their_node_id.clone(),
2414                                                         updates,
2415                                                 });
2416                                         }
2417                                         if let Some(msg) = closing_signed {
2418                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2419                                                         node_id: their_node_id.clone(),
2420                                                         msg,
2421                                                 });
2422                                         }
2423                                         (pending_forwards, pending_failures, chan.get().get_short_channel_id().expect("RAA should only work on a short-id-available channel"))
2424                                 },
2425                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2426                         }
2427                 };
2428                 for failure in pending_failures.drain(..) {
2429                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2430                 }
2431                 self.forward_htlcs(&mut [(short_channel_id, pending_forwards)]);
2432
2433                 Ok(())
2434         }
2435
2436         fn internal_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2437                 let mut channel_lock = self.channel_state.lock().unwrap();
2438                 let channel_state = channel_lock.borrow_parts();
2439                 match channel_state.by_id.entry(msg.channel_id) {
2440                         hash_map::Entry::Occupied(mut chan) => {
2441                                 if chan.get().get_their_node_id() != *their_node_id {
2442                                         //TODO: here and below MsgHandleErrInternal, #153 case
2443                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2444                                 }
2445                                 try_chan_entry!(self, chan.get_mut().update_fee(&*self.fee_estimator, &msg), channel_state, chan);
2446                         },
2447                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2448                 }
2449                 Ok(())
2450         }
2451
2452         fn internal_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2453                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2454                 let channel_state = channel_state_lock.borrow_parts();
2455
2456                 match channel_state.by_id.entry(msg.channel_id) {
2457                         hash_map::Entry::Occupied(mut chan) => {
2458                                 if chan.get().get_their_node_id() != *their_node_id {
2459                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2460                                 }
2461                                 if !chan.get().is_usable() {
2462                                         return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Got an announcement_signatures before we were ready for it", action: Some(msgs::ErrorAction::IgnoreError)}));
2463                                 }
2464
2465                                 let our_node_id = self.get_our_node_id();
2466                                 let (announcement, our_bitcoin_sig) =
2467                                         try_chan_entry!(self, chan.get_mut().get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone()), channel_state, chan);
2468
2469                                 let were_node_one = announcement.node_id_1 == our_node_id;
2470                                 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
2471                                 if self.secp_ctx.verify(&msghash, &msg.node_signature, if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 }).is_err() ||
2472                                                 self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 }).is_err() {
2473                                         try_chan_entry!(self, Err(ChannelError::Close("Bad announcement_signatures node_signature")), channel_state, chan);
2474                                 }
2475
2476                                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2477
2478                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
2479                                         msg: msgs::ChannelAnnouncement {
2480                                                 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
2481                                                 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
2482                                                 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
2483                                                 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
2484                                                 contents: announcement,
2485                                         },
2486                                         update_msg: self.get_channel_update(chan.get()).unwrap(), // can only fail if we're not in a ready state
2487                                 });
2488                         },
2489                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2490                 }
2491                 Ok(())
2492         }
2493
2494         fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
2495                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2496                 let channel_state = channel_state_lock.borrow_parts();
2497
2498                 match channel_state.by_id.entry(msg.channel_id) {
2499                         hash_map::Entry::Occupied(mut chan) => {
2500                                 if chan.get().get_their_node_id() != *their_node_id {
2501                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2502                                 }
2503                                 let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, mut order, shutdown) =
2504                                         try_chan_entry!(self, chan.get_mut().channel_reestablish(msg), channel_state, chan);
2505                                 if let Some(monitor) = channel_monitor {
2506                                         if let Err(e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
2507                                                 // channel_reestablish doesn't guarantee the order it returns is sensical
2508                                                 // for the messages it returns, but if we're setting what messages to
2509                                                 // re-transmit on monitor update success, we need to make sure it is sane.
2510                                                 if revoke_and_ack.is_none() {
2511                                                         order = RAACommitmentOrder::CommitmentFirst;
2512                                                 }
2513                                                 if commitment_update.is_none() {
2514                                                         order = RAACommitmentOrder::RevokeAndACKFirst;
2515                                                 }
2516                                                 return_monitor_err!(self, e, channel_state, chan, order);
2517                                                 //TODO: Resend the funding_locked if needed once we get the monitor running again
2518                                         }
2519                                 }
2520                                 if let Some(msg) = funding_locked {
2521                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2522                                                 node_id: their_node_id.clone(),
2523                                                 msg
2524                                         });
2525                                 }
2526                                 macro_rules! send_raa { () => {
2527                                         if let Some(msg) = revoke_and_ack {
2528                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2529                                                         node_id: their_node_id.clone(),
2530                                                         msg
2531                                                 });
2532                                         }
2533                                 } }
2534                                 macro_rules! send_cu { () => {
2535                                         if let Some(updates) = commitment_update {
2536                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2537                                                         node_id: their_node_id.clone(),
2538                                                         updates
2539                                                 });
2540                                         }
2541                                 } }
2542                                 match order {
2543                                         RAACommitmentOrder::RevokeAndACKFirst => {
2544                                                 send_raa!();
2545                                                 send_cu!();
2546                                         },
2547                                         RAACommitmentOrder::CommitmentFirst => {
2548                                                 send_cu!();
2549                                                 send_raa!();
2550                                         },
2551                                 }
2552                                 if let Some(msg) = shutdown {
2553                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2554                                                 node_id: their_node_id.clone(),
2555                                                 msg,
2556                                         });
2557                                 }
2558                                 Ok(())
2559                         },
2560                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2561                 }
2562         }
2563
2564         /// Begin Update fee process. Allowed only on an outbound channel.
2565         /// If successful, will generate a UpdateHTLCs event, so you should probably poll
2566         /// PeerManager::process_events afterwards.
2567         /// Note: This API is likely to change!
2568         #[doc(hidden)]
2569         pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u64) -> Result<(), APIError> {
2570                 let _ = self.total_consistency_lock.read().unwrap();
2571                 let their_node_id;
2572                 let err: Result<(), _> = loop {
2573                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2574                         let channel_state = channel_state_lock.borrow_parts();
2575
2576                         match channel_state.by_id.entry(channel_id) {
2577                                 hash_map::Entry::Vacant(_) => return Err(APIError::APIMisuseError{err: "Failed to find corresponding channel"}),
2578                                 hash_map::Entry::Occupied(mut chan) => {
2579                                         if !chan.get().is_outbound() {
2580                                                 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel"});
2581                                         }
2582                                         if chan.get().is_awaiting_monitor_update() {
2583                                                 return Err(APIError::MonitorUpdateFailed);
2584                                         }
2585                                         if !chan.get().is_live() {
2586                                                 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected"});
2587                                         }
2588                                         their_node_id = chan.get().get_their_node_id();
2589                                         if let Some((update_fee, commitment_signed, chan_monitor)) =
2590                                                         break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw), channel_state, chan)
2591                                         {
2592                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2593                                                         unimplemented!();
2594                                                 }
2595                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2596                                                         node_id: chan.get().get_their_node_id(),
2597                                                         updates: msgs::CommitmentUpdate {
2598                                                                 update_add_htlcs: Vec::new(),
2599                                                                 update_fulfill_htlcs: Vec::new(),
2600                                                                 update_fail_htlcs: Vec::new(),
2601                                                                 update_fail_malformed_htlcs: Vec::new(),
2602                                                                 update_fee: Some(update_fee),
2603                                                                 commitment_signed,
2604                                                         },
2605                                                 });
2606                                         }
2607                                 },
2608                         }
2609                         return Ok(())
2610                 };
2611
2612                 match handle_error!(self, err, their_node_id) {
2613                         Ok(_) => unreachable!(),
2614                         Err(e) => {
2615                                 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
2616                                 } else {
2617                                         log_error!(self, "Got bad keys: {}!", e.err);
2618                                         let mut channel_state = self.channel_state.lock().unwrap();
2619                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
2620                                                 node_id: their_node_id,
2621                                                 action: e.action,
2622                                         });
2623                                 }
2624                                 Err(APIError::APIMisuseError { err: e.err })
2625                         },
2626                 }
2627         }
2628 }
2629
2630 impl events::MessageSendEventsProvider for ChannelManager {
2631         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
2632                 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2633                 // user to serialize a ChannelManager with pending events in it and lose those events on
2634                 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2635                 {
2636                         //TODO: This behavior should be documented.
2637                         for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2638                                 if let Some(preimage) = htlc_update.payment_preimage {
2639                                         log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2640                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2641                                 } else {
2642                                         log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2643                                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
2644                                 }
2645                         }
2646                 }
2647
2648                 let mut ret = Vec::new();
2649                 let mut channel_state = self.channel_state.lock().unwrap();
2650                 mem::swap(&mut ret, &mut channel_state.pending_msg_events);
2651                 ret
2652         }
2653 }
2654
2655 impl events::EventsProvider for ChannelManager {
2656         fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
2657                 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2658                 // user to serialize a ChannelManager with pending events in it and lose those events on
2659                 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2660                 {
2661                         //TODO: This behavior should be documented.
2662                         for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2663                                 if let Some(preimage) = htlc_update.payment_preimage {
2664                                         log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2665                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2666                                 } else {
2667                                         log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2668                                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
2669                                 }
2670                         }
2671                 }
2672
2673                 let mut ret = Vec::new();
2674                 let mut pending_events = self.pending_events.lock().unwrap();
2675                 mem::swap(&mut ret, &mut *pending_events);
2676                 ret
2677         }
2678 }
2679
2680 impl ChainListener for ChannelManager {
2681         fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
2682                 let header_hash = header.bitcoin_hash();
2683                 log_trace!(self, "Block {} at height {} connected with {} txn matched", header_hash, height, txn_matched.len());
2684                 let _ = self.total_consistency_lock.read().unwrap();
2685                 let mut failed_channels = Vec::new();
2686                 {
2687                         let mut channel_lock = self.channel_state.lock().unwrap();
2688                         let channel_state = channel_lock.borrow_parts();
2689                         let short_to_id = channel_state.short_to_id;
2690                         let pending_msg_events = channel_state.pending_msg_events;
2691                         channel_state.by_id.retain(|_, channel| {
2692                                 let chan_res = channel.block_connected(header, height, txn_matched, indexes_of_txn_matched);
2693                                 if let Ok(Some(funding_locked)) = chan_res {
2694                                         pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2695                                                 node_id: channel.get_their_node_id(),
2696                                                 msg: funding_locked,
2697                                         });
2698                                         if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
2699                                                 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2700                                                         node_id: channel.get_their_node_id(),
2701                                                         msg: announcement_sigs,
2702                                                 });
2703                                         }
2704                                         short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
2705                                 } else if let Err(e) = chan_res {
2706                                         pending_msg_events.push(events::MessageSendEvent::HandleError {
2707                                                 node_id: channel.get_their_node_id(),
2708                                                 action: Some(msgs::ErrorAction::SendErrorMessage { msg: e }),
2709                                         });
2710                                         return false;
2711                                 }
2712                                 if let Some(funding_txo) = channel.get_funding_txo() {
2713                                         for tx in txn_matched {
2714                                                 for inp in tx.input.iter() {
2715                                                         if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
2716                                                                 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()));
2717                                                                 if let Some(short_id) = channel.get_short_channel_id() {
2718                                                                         short_to_id.remove(&short_id);
2719                                                                 }
2720                                                                 // It looks like our counterparty went on-chain. We go ahead and
2721                                                                 // broadcast our latest local state as well here, just in case its
2722                                                                 // some kind of SPV attack, though we expect these to be dropped.
2723                                                                 failed_channels.push(channel.force_shutdown());
2724                                                                 if let Ok(update) = self.get_channel_update(&channel) {
2725                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2726                                                                                 msg: update
2727                                                                         });
2728                                                                 }
2729                                                                 return false;
2730                                                         }
2731                                                 }
2732                                         }
2733                                 }
2734                                 if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height) {
2735                                         if let Some(short_id) = channel.get_short_channel_id() {
2736                                                 short_to_id.remove(&short_id);
2737                                         }
2738                                         failed_channels.push(channel.force_shutdown());
2739                                         // If would_broadcast_at_height() is true, the channel_monitor will broadcast
2740                                         // the latest local tx for us, so we should skip that here (it doesn't really
2741                                         // hurt anything, but does make tests a bit simpler).
2742                                         failed_channels.last_mut().unwrap().0 = Vec::new();
2743                                         if let Ok(update) = self.get_channel_update(&channel) {
2744                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2745                                                         msg: update
2746                                                 });
2747                                         }
2748                                         return false;
2749                                 }
2750                                 true
2751                         });
2752                 }
2753                 for failure in failed_channels.drain(..) {
2754                         self.finish_force_close_channel(failure);
2755                 }
2756                 self.latest_block_height.store(height as usize, Ordering::Release);
2757                 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header_hash;
2758         }
2759
2760         /// We force-close the channel without letting our counterparty participate in the shutdown
2761         fn block_disconnected(&self, header: &BlockHeader) {
2762                 let _ = self.total_consistency_lock.read().unwrap();
2763                 let mut failed_channels = Vec::new();
2764                 {
2765                         let mut channel_lock = self.channel_state.lock().unwrap();
2766                         let channel_state = channel_lock.borrow_parts();
2767                         let short_to_id = channel_state.short_to_id;
2768                         let pending_msg_events = channel_state.pending_msg_events;
2769                         channel_state.by_id.retain(|_,  v| {
2770                                 if v.block_disconnected(header) {
2771                                         if let Some(short_id) = v.get_short_channel_id() {
2772                                                 short_to_id.remove(&short_id);
2773                                         }
2774                                         failed_channels.push(v.force_shutdown());
2775                                         if let Ok(update) = self.get_channel_update(&v) {
2776                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2777                                                         msg: update
2778                                                 });
2779                                         }
2780                                         false
2781                                 } else {
2782                                         true
2783                                 }
2784                         });
2785                 }
2786                 for failure in failed_channels.drain(..) {
2787                         self.finish_force_close_channel(failure);
2788                 }
2789                 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
2790                 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
2791         }
2792 }
2793
2794 impl ChannelMessageHandler for ChannelManager {
2795         //TODO: Handle errors and close channel (or so)
2796         fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), HandleError> {
2797                 let _ = self.total_consistency_lock.read().unwrap();
2798                 handle_error!(self, self.internal_open_channel(their_node_id, msg), their_node_id)
2799         }
2800
2801         fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), HandleError> {
2802                 let _ = self.total_consistency_lock.read().unwrap();
2803                 handle_error!(self, self.internal_accept_channel(their_node_id, msg), their_node_id)
2804         }
2805
2806         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), HandleError> {
2807                 let _ = self.total_consistency_lock.read().unwrap();
2808                 handle_error!(self, self.internal_funding_created(their_node_id, msg), their_node_id)
2809         }
2810
2811         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), HandleError> {
2812                 let _ = self.total_consistency_lock.read().unwrap();
2813                 handle_error!(self, self.internal_funding_signed(their_node_id, msg), their_node_id)
2814         }
2815
2816         fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), HandleError> {
2817                 let _ = self.total_consistency_lock.read().unwrap();
2818                 handle_error!(self, self.internal_funding_locked(their_node_id, msg), their_node_id)
2819         }
2820
2821         fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), HandleError> {
2822                 let _ = self.total_consistency_lock.read().unwrap();
2823                 handle_error!(self, self.internal_shutdown(their_node_id, msg), their_node_id)
2824         }
2825
2826         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), HandleError> {
2827                 let _ = self.total_consistency_lock.read().unwrap();
2828                 handle_error!(self, self.internal_closing_signed(their_node_id, msg), their_node_id)
2829         }
2830
2831         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), msgs::HandleError> {
2832                 let _ = self.total_consistency_lock.read().unwrap();
2833                 handle_error!(self, self.internal_update_add_htlc(their_node_id, msg), their_node_id)
2834         }
2835
2836         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), HandleError> {
2837                 let _ = self.total_consistency_lock.read().unwrap();
2838                 handle_error!(self, self.internal_update_fulfill_htlc(their_node_id, msg), their_node_id)
2839         }
2840
2841         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), HandleError> {
2842                 let _ = self.total_consistency_lock.read().unwrap();
2843                 handle_error!(self, self.internal_update_fail_htlc(their_node_id, msg), their_node_id)
2844         }
2845
2846         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), HandleError> {
2847                 let _ = self.total_consistency_lock.read().unwrap();
2848                 handle_error!(self, self.internal_update_fail_malformed_htlc(their_node_id, msg), their_node_id)
2849         }
2850
2851         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), HandleError> {
2852                 let _ = self.total_consistency_lock.read().unwrap();
2853                 handle_error!(self, self.internal_commitment_signed(their_node_id, msg), their_node_id)
2854         }
2855
2856         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), HandleError> {
2857                 let _ = self.total_consistency_lock.read().unwrap();
2858                 handle_error!(self, self.internal_revoke_and_ack(their_node_id, msg), their_node_id)
2859         }
2860
2861         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), HandleError> {
2862                 let _ = self.total_consistency_lock.read().unwrap();
2863                 handle_error!(self, self.internal_update_fee(their_node_id, msg), their_node_id)
2864         }
2865
2866         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), HandleError> {
2867                 let _ = self.total_consistency_lock.read().unwrap();
2868                 handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
2869         }
2870
2871         fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), HandleError> {
2872                 let _ = self.total_consistency_lock.read().unwrap();
2873                 handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), their_node_id)
2874         }
2875
2876         fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
2877                 let _ = self.total_consistency_lock.read().unwrap();
2878                 let mut failed_channels = Vec::new();
2879                 let mut failed_payments = Vec::new();
2880                 {
2881                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2882                         let channel_state = channel_state_lock.borrow_parts();
2883                         let short_to_id = channel_state.short_to_id;
2884                         let pending_msg_events = channel_state.pending_msg_events;
2885                         if no_connection_possible {
2886                                 log_debug!(self, "Failing all channels with {} due to no_connection_possible", log_pubkey!(their_node_id));
2887                                 channel_state.by_id.retain(|_, chan| {
2888                                         if chan.get_their_node_id() == *their_node_id {
2889                                                 if let Some(short_id) = chan.get_short_channel_id() {
2890                                                         short_to_id.remove(&short_id);
2891                                                 }
2892                                                 failed_channels.push(chan.force_shutdown());
2893                                                 if let Ok(update) = self.get_channel_update(&chan) {
2894                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2895                                                                 msg: update
2896                                                         });
2897                                                 }
2898                                                 false
2899                                         } else {
2900                                                 true
2901                                         }
2902                                 });
2903                         } else {
2904                                 log_debug!(self, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(their_node_id));
2905                                 channel_state.by_id.retain(|_, chan| {
2906                                         if chan.get_their_node_id() == *their_node_id {
2907                                                 //TODO: mark channel disabled (and maybe announce such after a timeout).
2908                                                 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused();
2909                                                 if !failed_adds.is_empty() {
2910                                                         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
2911                                                         failed_payments.push((chan_update, failed_adds));
2912                                                 }
2913                                                 if chan.is_shutdown() {
2914                                                         if let Some(short_id) = chan.get_short_channel_id() {
2915                                                                 short_to_id.remove(&short_id);
2916                                                         }
2917                                                         return false;
2918                                                 }
2919                                         }
2920                                         true
2921                                 })
2922                         }
2923                 }
2924                 for failure in failed_channels.drain(..) {
2925                         self.finish_force_close_channel(failure);
2926                 }
2927                 for (chan_update, mut htlc_sources) in failed_payments {
2928                         for (htlc_source, payment_hash) in htlc_sources.drain(..) {
2929                                 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
2930                         }
2931                 }
2932         }
2933
2934         fn peer_connected(&self, their_node_id: &PublicKey) {
2935                 log_debug!(self, "Generating channel_reestablish events for {}", log_pubkey!(their_node_id));
2936
2937                 let _ = self.total_consistency_lock.read().unwrap();
2938                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2939                 let channel_state = channel_state_lock.borrow_parts();
2940                 let pending_msg_events = channel_state.pending_msg_events;
2941                 channel_state.by_id.retain(|_, chan| {
2942                         if chan.get_their_node_id() == *their_node_id {
2943                                 if !chan.have_received_message() {
2944                                         // If we created this (outbound) channel while we were disconnected from the
2945                                         // peer we probably failed to send the open_channel message, which is now
2946                                         // lost. We can't have had anything pending related to this channel, so we just
2947                                         // drop it.
2948                                         false
2949                                 } else {
2950                                         pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
2951                                                 node_id: chan.get_their_node_id(),
2952                                                 msg: chan.get_channel_reestablish(),
2953                                         });
2954                                         true
2955                                 }
2956                         } else { true }
2957                 });
2958                 //TODO: Also re-broadcast announcement_signatures
2959         }
2960
2961         fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
2962                 let _ = self.total_consistency_lock.read().unwrap();
2963
2964                 if msg.channel_id == [0; 32] {
2965                         for chan in self.list_channels() {
2966                                 if chan.remote_network_id == *their_node_id {
2967                                         self.force_close_channel(&chan.channel_id);
2968                                 }
2969                         }
2970                 } else {
2971                         self.force_close_channel(&msg.channel_id);
2972                 }
2973         }
2974 }
2975
2976 const SERIALIZATION_VERSION: u8 = 1;
2977 const MIN_SERIALIZATION_VERSION: u8 = 1;
2978
2979 impl Writeable for PendingForwardHTLCInfo {
2980         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2981                 if let &Some(ref onion) = &self.onion_packet {
2982                         1u8.write(writer)?;
2983                         onion.write(writer)?;
2984                 } else {
2985                         0u8.write(writer)?;
2986                 }
2987                 self.incoming_shared_secret.write(writer)?;
2988                 self.payment_hash.write(writer)?;
2989                 self.short_channel_id.write(writer)?;
2990                 self.amt_to_forward.write(writer)?;
2991                 self.outgoing_cltv_value.write(writer)?;
2992                 Ok(())
2993         }
2994 }
2995
2996 impl<R: ::std::io::Read> Readable<R> for PendingForwardHTLCInfo {
2997         fn read(reader: &mut R) -> Result<PendingForwardHTLCInfo, DecodeError> {
2998                 let onion_packet = match <u8 as Readable<R>>::read(reader)? {
2999                         0 => None,
3000                         1 => Some(msgs::OnionPacket::read(reader)?),
3001                         _ => return Err(DecodeError::InvalidValue),
3002                 };
3003                 Ok(PendingForwardHTLCInfo {
3004                         onion_packet,
3005                         incoming_shared_secret: Readable::read(reader)?,
3006                         payment_hash: Readable::read(reader)?,
3007                         short_channel_id: Readable::read(reader)?,
3008                         amt_to_forward: Readable::read(reader)?,
3009                         outgoing_cltv_value: Readable::read(reader)?,
3010                 })
3011         }
3012 }
3013
3014 impl Writeable for HTLCFailureMsg {
3015         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3016                 match self {
3017                         &HTLCFailureMsg::Relay(ref fail_msg) => {
3018                                 0u8.write(writer)?;
3019                                 fail_msg.write(writer)?;
3020                         },
3021                         &HTLCFailureMsg::Malformed(ref fail_msg) => {
3022                                 1u8.write(writer)?;
3023                                 fail_msg.write(writer)?;
3024                         }
3025                 }
3026                 Ok(())
3027         }
3028 }
3029
3030 impl<R: ::std::io::Read> Readable<R> for HTLCFailureMsg {
3031         fn read(reader: &mut R) -> Result<HTLCFailureMsg, DecodeError> {
3032                 match <u8 as Readable<R>>::read(reader)? {
3033                         0 => Ok(HTLCFailureMsg::Relay(Readable::read(reader)?)),
3034                         1 => Ok(HTLCFailureMsg::Malformed(Readable::read(reader)?)),
3035                         _ => Err(DecodeError::InvalidValue),
3036                 }
3037         }
3038 }
3039
3040 impl Writeable for PendingHTLCStatus {
3041         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3042                 match self {
3043                         &PendingHTLCStatus::Forward(ref forward_info) => {
3044                                 0u8.write(writer)?;
3045                                 forward_info.write(writer)?;
3046                         },
3047                         &PendingHTLCStatus::Fail(ref fail_msg) => {
3048                                 1u8.write(writer)?;
3049                                 fail_msg.write(writer)?;
3050                         }
3051                 }
3052                 Ok(())
3053         }
3054 }
3055
3056 impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
3057         fn read(reader: &mut R) -> Result<PendingHTLCStatus, DecodeError> {
3058                 match <u8 as Readable<R>>::read(reader)? {
3059                         0 => Ok(PendingHTLCStatus::Forward(Readable::read(reader)?)),
3060                         1 => Ok(PendingHTLCStatus::Fail(Readable::read(reader)?)),
3061                         _ => Err(DecodeError::InvalidValue),
3062                 }
3063         }
3064 }
3065
3066 impl_writeable!(HTLCPreviousHopData, 0, {
3067         short_channel_id,
3068         htlc_id,
3069         incoming_packet_shared_secret
3070 });
3071
3072 impl Writeable for HTLCSource {
3073         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3074                 match self {
3075                         &HTLCSource::PreviousHopData(ref hop_data) => {
3076                                 0u8.write(writer)?;
3077                                 hop_data.write(writer)?;
3078                         },
3079                         &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } => {
3080                                 1u8.write(writer)?;
3081                                 route.write(writer)?;
3082                                 session_priv.write(writer)?;
3083                                 first_hop_htlc_msat.write(writer)?;
3084                         }
3085                 }
3086                 Ok(())
3087         }
3088 }
3089
3090 impl<R: ::std::io::Read> Readable<R> for HTLCSource {
3091         fn read(reader: &mut R) -> Result<HTLCSource, DecodeError> {
3092                 match <u8 as Readable<R>>::read(reader)? {
3093                         0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
3094                         1 => Ok(HTLCSource::OutboundRoute {
3095                                 route: Readable::read(reader)?,
3096                                 session_priv: Readable::read(reader)?,
3097                                 first_hop_htlc_msat: Readable::read(reader)?,
3098                         }),
3099                         _ => Err(DecodeError::InvalidValue),
3100                 }
3101         }
3102 }
3103
3104 impl Writeable for HTLCFailReason {
3105         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3106                 match self {
3107                         &HTLCFailReason::ErrorPacket { ref err } => {
3108                                 0u8.write(writer)?;
3109                                 err.write(writer)?;
3110                         },
3111                         &HTLCFailReason::Reason { ref failure_code, ref data } => {
3112                                 1u8.write(writer)?;
3113                                 failure_code.write(writer)?;
3114                                 data.write(writer)?;
3115                         }
3116                 }
3117                 Ok(())
3118         }
3119 }
3120
3121 impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
3122         fn read(reader: &mut R) -> Result<HTLCFailReason, DecodeError> {
3123                 match <u8 as Readable<R>>::read(reader)? {
3124                         0 => Ok(HTLCFailReason::ErrorPacket { err: Readable::read(reader)? }),
3125                         1 => Ok(HTLCFailReason::Reason {
3126                                 failure_code: Readable::read(reader)?,
3127                                 data: Readable::read(reader)?,
3128                         }),
3129                         _ => Err(DecodeError::InvalidValue),
3130                 }
3131         }
3132 }
3133
3134 impl_writeable!(HTLCForwardInfo, 0, {
3135         prev_short_channel_id,
3136         prev_htlc_id,
3137         forward_info
3138 });
3139
3140 impl Writeable for ChannelManager {
3141         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3142                 let _ = self.total_consistency_lock.write().unwrap();
3143
3144                 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
3145                 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
3146
3147                 self.genesis_hash.write(writer)?;
3148                 (self.latest_block_height.load(Ordering::Acquire) as u32).write(writer)?;
3149                 self.last_block_hash.lock().unwrap().write(writer)?;
3150
3151                 let channel_state = self.channel_state.lock().unwrap();
3152                 let mut unfunded_channels = 0;
3153                 for (_, channel) in channel_state.by_id.iter() {
3154                         if !channel.is_funding_initiated() {
3155                                 unfunded_channels += 1;
3156                         }
3157                 }
3158                 ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
3159                 for (_, channel) in channel_state.by_id.iter() {
3160                         if channel.is_funding_initiated() {
3161                                 channel.write(writer)?;
3162                         }
3163                 }
3164
3165                 (channel_state.forward_htlcs.len() as u64).write(writer)?;
3166                 for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
3167                         short_channel_id.write(writer)?;
3168                         (pending_forwards.len() as u64).write(writer)?;
3169                         for forward in pending_forwards {
3170                                 forward.write(writer)?;
3171                         }
3172                 }
3173
3174                 (channel_state.claimable_htlcs.len() as u64).write(writer)?;
3175                 for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
3176                         payment_hash.write(writer)?;
3177                         (previous_hops.len() as u64).write(writer)?;
3178                         for previous_hop in previous_hops {
3179                                 previous_hop.write(writer)?;
3180                         }
3181                 }
3182
3183                 Ok(())
3184         }
3185 }
3186
3187 /// Arguments for the creation of a ChannelManager that are not deserialized.
3188 ///
3189 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
3190 /// is:
3191 /// 1) Deserialize all stored ChannelMonitors.
3192 /// 2) Deserialize the ChannelManager by filling in this struct and calling <(Sha256dHash,
3193 ///    ChannelManager)>::read(reader, args).
3194 ///    This may result in closing some Channels if the ChannelMonitor is newer than the stored
3195 ///    ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
3196 /// 3) Register all relevant ChannelMonitor outpoints with your chain watch mechanism using
3197 ///    ChannelMonitor::get_monitored_outpoints and ChannelMonitor::get_funding_txo().
3198 /// 4) Reconnect blocks on your ChannelMonitors.
3199 /// 5) Move the ChannelMonitors into your local ManyChannelMonitor.
3200 /// 6) Disconnect/connect blocks on the ChannelManager.
3201 /// 7) Register the new ChannelManager with your ChainWatchInterface (this does not happen
3202 ///    automatically as it does in ChannelManager::new()).
3203 pub struct ChannelManagerReadArgs<'a> {
3204         /// The keys provider which will give us relevant keys. Some keys will be loaded during
3205         /// deserialization.
3206         pub keys_manager: Arc<KeysInterface>,
3207
3208         /// The fee_estimator for use in the ChannelManager in the future.
3209         ///
3210         /// No calls to the FeeEstimator will be made during deserialization.
3211         pub fee_estimator: Arc<FeeEstimator>,
3212         /// The ManyChannelMonitor for use in the ChannelManager in the future.
3213         ///
3214         /// No calls to the ManyChannelMonitor will be made during deserialization. It is assumed that
3215         /// you have deserialized ChannelMonitors separately and will add them to your
3216         /// ManyChannelMonitor after deserializing this ChannelManager.
3217         pub monitor: Arc<ManyChannelMonitor>,
3218         /// The ChainWatchInterface for use in the ChannelManager in the future.
3219         ///
3220         /// No calls to the ChainWatchInterface will be made during deserialization.
3221         pub chain_monitor: Arc<ChainWatchInterface>,
3222         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
3223         /// used to broadcast the latest local commitment transactions of channels which must be
3224         /// force-closed during deserialization.
3225         pub tx_broadcaster: Arc<BroadcasterInterface>,
3226         /// The Logger for use in the ChannelManager and which may be used to log information during
3227         /// deserialization.
3228         pub logger: Arc<Logger>,
3229         /// Default settings used for new channels. Any existing channels will continue to use the
3230         /// runtime settings which were stored when the ChannelManager was serialized.
3231         pub default_config: UserConfig,
3232
3233         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
3234         /// value.get_funding_txo() should be the key).
3235         ///
3236         /// If a monitor is inconsistent with the channel state during deserialization the channel will
3237         /// be force-closed using the data in the channelmonitor and the Channel will be dropped. This
3238         /// is true for missing channels as well. If there is a monitor missing for which we find
3239         /// channel data Err(DecodeError::InvalidValue) will be returned.
3240         ///
3241         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
3242         /// this struct.
3243         pub channel_monitors: &'a HashMap<OutPoint, &'a ChannelMonitor>,
3244 }
3245
3246 impl<'a, R : ::std::io::Read> ReadableArgs<R, ChannelManagerReadArgs<'a>> for (Sha256dHash, ChannelManager) {
3247         fn read(reader: &mut R, args: ChannelManagerReadArgs<'a>) -> Result<Self, DecodeError> {
3248                 let _ver: u8 = Readable::read(reader)?;
3249                 let min_ver: u8 = Readable::read(reader)?;
3250                 if min_ver > SERIALIZATION_VERSION {
3251                         return Err(DecodeError::UnknownVersion);
3252                 }
3253
3254                 let genesis_hash: Sha256dHash = Readable::read(reader)?;
3255                 let latest_block_height: u32 = Readable::read(reader)?;
3256                 let last_block_hash: Sha256dHash = Readable::read(reader)?;
3257
3258                 let mut closed_channels = Vec::new();
3259
3260                 let channel_count: u64 = Readable::read(reader)?;
3261                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
3262                 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3263                 let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3264                 for _ in 0..channel_count {
3265                         let mut channel: Channel = ReadableArgs::read(reader, args.logger.clone())?;
3266                         if channel.last_block_connected != last_block_hash {
3267                                 return Err(DecodeError::InvalidValue);
3268                         }
3269
3270                         let funding_txo = channel.channel_monitor().get_funding_txo().ok_or(DecodeError::InvalidValue)?;
3271                         funding_txo_set.insert(funding_txo.clone());
3272                         if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
3273                                 if channel.get_cur_local_commitment_transaction_number() != monitor.get_cur_local_commitment_number() ||
3274                                                 channel.get_revoked_remote_commitment_transaction_number() != monitor.get_min_seen_secret() ||
3275                                                 channel.get_cur_remote_commitment_transaction_number() != monitor.get_cur_remote_commitment_number() {
3276                                         let mut force_close_res = channel.force_shutdown();
3277                                         force_close_res.0 = monitor.get_latest_local_commitment_txn();
3278                                         closed_channels.push(force_close_res);
3279                                 } else {
3280                                         if let Some(short_channel_id) = channel.get_short_channel_id() {
3281                                                 short_to_id.insert(short_channel_id, channel.channel_id());
3282                                         }
3283                                         by_id.insert(channel.channel_id(), channel);
3284                                 }
3285                         } else {
3286                                 return Err(DecodeError::InvalidValue);
3287                         }
3288                 }
3289
3290                 for (ref funding_txo, ref monitor) in args.channel_monitors.iter() {
3291                         if !funding_txo_set.contains(funding_txo) {
3292                                 closed_channels.push((monitor.get_latest_local_commitment_txn(), Vec::new()));
3293                         }
3294                 }
3295
3296                 let forward_htlcs_count: u64 = Readable::read(reader)?;
3297                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
3298                 for _ in 0..forward_htlcs_count {
3299                         let short_channel_id = Readable::read(reader)?;
3300                         let pending_forwards_count: u64 = Readable::read(reader)?;
3301                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, 128));
3302                         for _ in 0..pending_forwards_count {
3303                                 pending_forwards.push(Readable::read(reader)?);
3304                         }
3305                         forward_htlcs.insert(short_channel_id, pending_forwards);
3306                 }
3307
3308                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
3309                 let mut claimable_htlcs = HashMap::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
3310                 for _ in 0..claimable_htlcs_count {
3311                         let payment_hash = Readable::read(reader)?;
3312                         let previous_hops_len: u64 = Readable::read(reader)?;
3313                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, 2));
3314                         for _ in 0..previous_hops_len {
3315                                 previous_hops.push(Readable::read(reader)?);
3316                         }
3317                         claimable_htlcs.insert(payment_hash, previous_hops);
3318                 }
3319
3320                 let channel_manager = ChannelManager {
3321                         genesis_hash,
3322                         fee_estimator: args.fee_estimator,
3323                         monitor: args.monitor,
3324                         chain_monitor: args.chain_monitor,
3325                         tx_broadcaster: args.tx_broadcaster,
3326
3327                         latest_block_height: AtomicUsize::new(latest_block_height as usize),
3328                         last_block_hash: Mutex::new(last_block_hash),
3329                         secp_ctx: Secp256k1::new(),
3330
3331                         channel_state: Mutex::new(ChannelHolder {
3332                                 by_id,
3333                                 short_to_id,
3334                                 next_forward: Instant::now(),
3335                                 forward_htlcs,
3336                                 claimable_htlcs,
3337                                 pending_msg_events: Vec::new(),
3338                         }),
3339                         our_network_key: args.keys_manager.get_node_secret(),
3340
3341                         pending_events: Mutex::new(Vec::new()),
3342                         total_consistency_lock: RwLock::new(()),
3343                         keys_manager: args.keys_manager,
3344                         logger: args.logger,
3345                         default_configuration: args.default_config,
3346                 };
3347
3348                 for close_res in closed_channels.drain(..) {
3349                         channel_manager.finish_force_close_channel(close_res);
3350                         //TODO: Broadcast channel update for closed channels, but only after we've made a
3351                         //connection or two.
3352                 }
3353
3354                 Ok((last_block_hash.clone(), channel_manager))
3355         }
3356 }
3357
3358 #[cfg(test)]
3359 mod tests {
3360         use chain::chaininterface;
3361         use chain::transaction::OutPoint;
3362         use chain::chaininterface::{ChainListener, ChainWatchInterface};
3363         use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor};
3364         use chain::keysinterface;
3365         use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
3366         use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,OnionKeys,PaymentFailReason,RAACommitmentOrder, PaymentPreimage, PaymentHash};
3367         use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, ManyChannelMonitor};
3368         use ln::channel::{ACCEPTED_HTLC_SCRIPT_WEIGHT, OFFERED_HTLC_SCRIPT_WEIGHT};
3369         use ln::router::{Route, RouteHop, Router};
3370         use ln::msgs;
3371         use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler};
3372         use util::test_utils;
3373         use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
3374         use util::errors::APIError;
3375         use util::logger::Logger;
3376         use util::ser::{Writeable, Writer, ReadableArgs};
3377         use util::config::UserConfig;
3378
3379         use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
3380         use bitcoin::util::bip143;
3381         use bitcoin::util::address::Address;
3382         use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
3383         use bitcoin::blockdata::block::{Block, BlockHeader};
3384         use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType};
3385         use bitcoin::blockdata::script::{Builder, Script};
3386         use bitcoin::blockdata::opcodes;
3387         use bitcoin::blockdata::constants::genesis_block;
3388         use bitcoin::network::constants::Network;
3389
3390         use hex;
3391
3392         use secp256k1::{Secp256k1, Message};
3393         use secp256k1::key::{PublicKey,SecretKey};
3394
3395         use crypto::sha2::Sha256;
3396         use crypto::digest::Digest;
3397
3398         use rand::{thread_rng,Rng};
3399
3400         use std::cell::RefCell;
3401         use std::collections::{BTreeSet, HashMap, HashSet};
3402         use std::default::Default;
3403         use std::rc::Rc;
3404         use std::sync::{Arc, Mutex};
3405         use std::sync::atomic::Ordering;
3406         use std::time::Instant;
3407         use std::mem;
3408
3409         fn build_test_onion_keys() -> Vec<OnionKeys> {
3410                 // Keys from BOLT 4, used in both test vector tests
3411                 let secp_ctx = Secp256k1::new();
3412
3413                 let route = Route {
3414                         hops: vec!(
3415                                         RouteHop {
3416                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
3417                                                 short_channel_id: 0, fee_msat: 0, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
3418                                         },
3419                                         RouteHop {
3420                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
3421                                                 short_channel_id: 0, fee_msat: 0, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
3422                                         },
3423                                         RouteHop {
3424                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
3425                                                 short_channel_id: 0, fee_msat: 0, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
3426                                         },
3427                                         RouteHop {
3428                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..]).unwrap(),
3429                                                 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
3430                                         },
3431                                         RouteHop {
3432                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145").unwrap()[..]).unwrap(),
3433                                                 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
3434                                         },
3435                         ),
3436                 };
3437
3438                 let session_priv = SecretKey::from_slice(&secp_ctx, &hex::decode("4141414141414141414141414141414141414141414141414141414141414141").unwrap()[..]).unwrap();
3439
3440                 let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
3441                 assert_eq!(onion_keys.len(), route.hops.len());
3442                 onion_keys
3443         }
3444
3445         #[test]
3446         fn onion_vectors() {
3447                 // Packet creation test vectors from BOLT 4
3448                 let onion_keys = build_test_onion_keys();
3449
3450                 assert_eq!(onion_keys[0].shared_secret[..], hex::decode("53eb63ea8a3fec3b3cd433b85cd62a4b145e1dda09391b348c4e1cd36a03ea66").unwrap()[..]);
3451                 assert_eq!(onion_keys[0].blinding_factor[..], hex::decode("2ec2e5da605776054187180343287683aa6a51b4b1c04d6dd49c45d8cffb3c36").unwrap()[..]);
3452                 assert_eq!(onion_keys[0].ephemeral_pubkey.serialize()[..], hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]);
3453                 assert_eq!(onion_keys[0].rho, hex::decode("ce496ec94def95aadd4bec15cdb41a740c9f2b62347c4917325fcc6fb0453986").unwrap()[..]);
3454                 assert_eq!(onion_keys[0].mu, hex::decode("b57061dc6d0a2b9f261ac410c8b26d64ac5506cbba30267a649c28c179400eba").unwrap()[..]);
3455
3456                 assert_eq!(onion_keys[1].shared_secret[..], hex::decode("a6519e98832a0b179f62123b3567c106db99ee37bef036e783263602f3488fae").unwrap()[..]);
3457                 assert_eq!(onion_keys[1].blinding_factor[..], hex::decode("bf66c28bc22e598cfd574a1931a2bafbca09163df2261e6d0056b2610dab938f").unwrap()[..]);
3458                 assert_eq!(onion_keys[1].ephemeral_pubkey.serialize()[..], hex::decode("028f9438bfbf7feac2e108d677e3a82da596be706cc1cf342b75c7b7e22bf4e6e2").unwrap()[..]);
3459                 assert_eq!(onion_keys[1].rho, hex::decode("450ffcabc6449094918ebe13d4f03e433d20a3d28a768203337bc40b6e4b2c59").unwrap()[..]);
3460                 assert_eq!(onion_keys[1].mu, hex::decode("05ed2b4a3fb023c2ff5dd6ed4b9b6ea7383f5cfe9d59c11d121ec2c81ca2eea9").unwrap()[..]);
3461
3462                 assert_eq!(onion_keys[2].shared_secret[..], hex::decode("3a6b412548762f0dbccce5c7ae7bb8147d1caf9b5471c34120b30bc9c04891cc").unwrap()[..]);
3463                 assert_eq!(onion_keys[2].blinding_factor[..], hex::decode("a1f2dadd184eb1627049673f18c6325814384facdee5bfd935d9cb031a1698a5").unwrap()[..]);
3464                 assert_eq!(onion_keys[2].ephemeral_pubkey.serialize()[..], hex::decode("03bfd8225241ea71cd0843db7709f4c222f62ff2d4516fd38b39914ab6b83e0da0").unwrap()[..]);
3465                 assert_eq!(onion_keys[2].rho, hex::decode("11bf5c4f960239cb37833936aa3d02cea82c0f39fd35f566109c41f9eac8deea").unwrap()[..]);
3466                 assert_eq!(onion_keys[2].mu, hex::decode("caafe2820fa00eb2eeb78695ae452eba38f5a53ed6d53518c5c6edf76f3f5b78").unwrap()[..]);
3467
3468                 assert_eq!(onion_keys[3].shared_secret[..], hex::decode("21e13c2d7cfe7e18836df50872466117a295783ab8aab0e7ecc8c725503ad02d").unwrap()[..]);
3469                 assert_eq!(onion_keys[3].blinding_factor[..], hex::decode("7cfe0b699f35525029ae0fa437c69d0f20f7ed4e3916133f9cacbb13c82ff262").unwrap()[..]);
3470                 assert_eq!(onion_keys[3].ephemeral_pubkey.serialize()[..], hex::decode("031dde6926381289671300239ea8e57ffaf9bebd05b9a5b95beaf07af05cd43595").unwrap()[..]);
3471                 assert_eq!(onion_keys[3].rho, hex::decode("cbe784ab745c13ff5cffc2fbe3e84424aa0fd669b8ead4ee562901a4a4e89e9e").unwrap()[..]);
3472                 assert_eq!(onion_keys[3].mu, hex::decode("5052aa1b3d9f0655a0932e50d42f0c9ba0705142c25d225515c45f47c0036ee9").unwrap()[..]);
3473
3474                 assert_eq!(onion_keys[4].shared_secret[..], hex::decode("b5756b9b542727dbafc6765a49488b023a725d631af688fc031217e90770c328").unwrap()[..]);
3475                 assert_eq!(onion_keys[4].blinding_factor[..], hex::decode("c96e00dddaf57e7edcd4fb5954be5b65b09f17cb6d20651b4e90315be5779205").unwrap()[..]);
3476                 assert_eq!(onion_keys[4].ephemeral_pubkey.serialize()[..], hex::decode("03a214ebd875aab6ddfd77f22c5e7311d7f77f17a169e599f157bbcdae8bf071f4").unwrap()[..]);
3477                 assert_eq!(onion_keys[4].rho, hex::decode("034e18b8cc718e8af6339106e706c52d8df89e2b1f7e9142d996acf88df8799b").unwrap()[..]);
3478                 assert_eq!(onion_keys[4].mu, hex::decode("8e45e5c61c2b24cb6382444db6698727afb063adecd72aada233d4bf273d975a").unwrap()[..]);
3479
3480                 // Test vectors below are flat-out wrong: they claim to set outgoing_cltv_value to non-0 :/
3481                 let payloads = vec!(
3482                         msgs::OnionHopData {
3483                                 realm: 0,
3484                                 data: msgs::OnionRealm0HopData {
3485                                         short_channel_id: 0,
3486                                         amt_to_forward: 0,
3487                                         outgoing_cltv_value: 0,
3488                                 },
3489                                 hmac: [0; 32],
3490                         },
3491                         msgs::OnionHopData {
3492                                 realm: 0,
3493                                 data: msgs::OnionRealm0HopData {
3494                                         short_channel_id: 0x0101010101010101,
3495                                         amt_to_forward: 0x0100000001,
3496                                         outgoing_cltv_value: 0,
3497                                 },
3498                                 hmac: [0; 32],
3499                         },
3500                         msgs::OnionHopData {
3501                                 realm: 0,
3502                                 data: msgs::OnionRealm0HopData {
3503                                         short_channel_id: 0x0202020202020202,
3504                                         amt_to_forward: 0x0200000002,
3505                                         outgoing_cltv_value: 0,
3506                                 },
3507                                 hmac: [0; 32],
3508                         },
3509                         msgs::OnionHopData {
3510                                 realm: 0,
3511                                 data: msgs::OnionRealm0HopData {
3512                                         short_channel_id: 0x0303030303030303,
3513                                         amt_to_forward: 0x0300000003,
3514                                         outgoing_cltv_value: 0,
3515                                 },
3516                                 hmac: [0; 32],
3517                         },
3518                         msgs::OnionHopData {
3519                                 realm: 0,
3520                                 data: msgs::OnionRealm0HopData {
3521                                         short_channel_id: 0x0404040404040404,
3522                                         amt_to_forward: 0x0400000004,
3523                                         outgoing_cltv_value: 0,
3524                                 },
3525                                 hmac: [0; 32],
3526                         },
3527                 );
3528
3529                 let packet = ChannelManager::construct_onion_packet(payloads, onion_keys, &PaymentHash([0x42; 32]));
3530                 // Just check the final packet encoding, as it includes all the per-hop vectors in it
3531                 // anyway...
3532                 assert_eq!(packet.encode(), hex::decode("0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619e5f14350c2a76fc232b5e46d421e9615471ab9e0bc887beff8c95fdb878f7b3a716a996c7845c93d90e4ecbb9bde4ece2f69425c99e4bc820e44485455f135edc0d10f7d61ab590531cf08000179a333a347f8b4072f216400406bdf3bf038659793d4a1fd7b246979e3150a0a4cb052c9ec69acf0f48c3d39cd55675fe717cb7d80ce721caad69320c3a469a202f1e468c67eaf7a7cd8226d0fd32f7b48084dca885d56047694762b67021713ca673929c163ec36e04e40ca8e1c6d17569419d3039d9a1ec866abe044a9ad635778b961fc0776dc832b3a451bd5d35072d2269cf9b040f6b7a7dad84fb114ed413b1426cb96ceaf83825665ed5a1d002c1687f92465b49ed4c7f0218ff8c6c7dd7221d589c65b3b9aaa71a41484b122846c7c7b57e02e679ea8469b70e14fe4f70fee4d87b910cf144be6fe48eef24da475c0b0bcc6565ae82cd3f4e3b24c76eaa5616c6111343306ab35c1fe5ca4a77c0e314ed7dba39d6f1e0de791719c241a939cc493bea2bae1c1e932679ea94d29084278513c77b899cc98059d06a27d171b0dbdf6bee13ddc4fc17a0c4d2827d488436b57baa167544138ca2e64a11b43ac8a06cd0c2fba2d4d900ed2d9205305e2d7383cc98dacb078133de5f6fb6bed2ef26ba92cea28aafc3b9948dd9ae5559e8bd6920b8cea462aa445ca6a95e0e7ba52961b181c79e73bd581821df2b10173727a810c92b83b5ba4a0403eb710d2ca10689a35bec6c3a708e9e92f7d78ff3c5d9989574b00c6736f84c199256e76e19e78f0c98a9d580b4a658c84fc8f2096c2fbea8f5f8c59d0fdacb3be2802ef802abbecb3aba4acaac69a0e965abd8981e9896b1f6ef9d60f7a164b371af869fd0e48073742825e9434fc54da837e120266d53302954843538ea7c6c3dbfb4ff3b2fdbe244437f2a153ccf7bdb4c92aa08102d4f3cff2ae5ef86fab4653595e6a5837fa2f3e29f27a9cde5966843fb847a4a61f1e76c281fe8bb2b0a181d096100db5a1a5ce7a910238251a43ca556712eaadea167fb4d7d75825e440f3ecd782036d7574df8bceacb397abefc5f5254d2722215c53ff54af8299aaaad642c6d72a14d27882d9bbd539e1cc7a527526ba89b8c037ad09120e98ab042d3e8652b31ae0e478516bfaf88efca9f3676ffe99d2819dcaeb7610a626695f53117665d267d3f7abebd6bbd6733f645c72c389f03855bdf1e4b8075b516569b118233a0f0971d24b83113c0b096f5216a207ca99a7cddc81c130923fe3d91e7508c9ac5f2e914ff5dccab9e558566fa14efb34ac98d878580814b94b73acbfde9072f30b881f7f0fff42d4045d1ace6322d86a97d164aa84d93a60498065cc7c20e636f5862dc81531a88c60305a2e59a985be327a6902e4bed986dbf4a0b50c217af0ea7fdf9ab37f9ea1a1aaa72f54cf40154ea9b269f1a7c09f9f43245109431a175d50e2db0132337baa0ef97eed0fcf20489da36b79a1172faccc2f7ded7c60e00694282d93359c4682135642bc81f433574aa8ef0c97b4ade7ca372c5ffc23c7eddd839bab4e0f14d6df15c9dbeab176bec8b5701cf054eb3072f6dadc98f88819042bf10c407516ee58bce33fbe3b3d86a54255e577db4598e30a135361528c101683a5fcde7e8ba53f3456254be8f45fe3a56120ae96ea3773631fcb3873aa3abd91bcff00bd38bd43697a2e789e00da6077482e7b1b1a677b5afae4c54e6cbdf7377b694eb7d7a5b913476a5be923322d3de06060fd5e819635232a2cf4f0731da13b8546d1d6d4f8d75b9fce6c2341a71b0ea6f780df54bfdb0dd5cd9855179f602f9172307c7268724c3618e6817abd793adc214a0dc0bc616816632f27ea336fb56dfd").unwrap());
3533         }
3534
3535         #[test]
3536         fn test_failure_packet_onion() {
3537                 // Returning Errors test vectors from BOLT 4
3538
3539                 let onion_keys = build_test_onion_keys();
3540                 let onion_error = ChannelManager::build_failure_packet(&onion_keys[4].shared_secret[..], 0x2002, &[0; 0]);
3541                 assert_eq!(onion_error.encode(), hex::decode("4c2fc8bc08510334b6833ad9c3e79cd1b52ae59dfe5c2a4b23ead50f09f7ee0b0002200200fe0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap());
3542
3543                 let onion_packet_1 = ChannelManager::encrypt_failure_packet(&onion_keys[4].shared_secret[..], &onion_error.encode()[..]);
3544                 assert_eq!(onion_packet_1.data, hex::decode("a5e6bd0c74cb347f10cce367f949098f2457d14c046fd8a22cb96efb30b0fdcda8cb9168b50f2fd45edd73c1b0c8b33002df376801ff58aaa94000bf8a86f92620f343baef38a580102395ae3abf9128d1047a0736ff9b83d456740ebbb4aeb3aa9737f18fb4afb4aa074fb26c4d702f42968888550a3bded8c05247e045b866baef0499f079fdaeef6538f31d44deafffdfd3afa2fb4ca9082b8f1c465371a9894dd8c243fb4847e004f5256b3e90e2edde4c9fb3082ddfe4d1e734cacd96ef0706bf63c9984e22dc98851bcccd1c3494351feb458c9c6af41c0044bea3c47552b1d992ae542b17a2d0bba1a096c78d169034ecb55b6e3a7263c26017f033031228833c1daefc0dedb8cf7c3e37c9c37ebfe42f3225c326e8bcfd338804c145b16e34e4").unwrap());
3545
3546                 let onion_packet_2 = ChannelManager::encrypt_failure_packet(&onion_keys[3].shared_secret[..], &onion_packet_1.data[..]);
3547                 assert_eq!(onion_packet_2.data, hex::decode("c49a1ce81680f78f5f2000cda36268de34a3f0a0662f55b4e837c83a8773c22aa081bab1616a0011585323930fa5b9fae0c85770a2279ff59ec427ad1bbff9001c0cd1497004bd2a0f68b50704cf6d6a4bf3c8b6a0833399a24b3456961ba00736785112594f65b6b2d44d9f5ea4e49b5e1ec2af978cbe31c67114440ac51a62081df0ed46d4a3df295da0b0fe25c0115019f03f15ec86fabb4c852f83449e812f141a9395b3f70b766ebbd4ec2fae2b6955bd8f32684c15abfe8fd3a6261e52650e8807a92158d9f1463261a925e4bfba44bd20b166d532f0017185c3a6ac7957adefe45559e3072c8dc35abeba835a8cb01a71a15c736911126f27d46a36168ca5ef7dccd4e2886212602b181463e0dd30185c96348f9743a02aca8ec27c0b90dca270").unwrap());
3548
3549                 let onion_packet_3 = ChannelManager::encrypt_failure_packet(&onion_keys[2].shared_secret[..], &onion_packet_2.data[..]);
3550                 assert_eq!(onion_packet_3.data, hex::decode("a5d3e8634cfe78b2307d87c6d90be6fe7855b4f2cc9b1dfb19e92e4b79103f61ff9ac25f412ddfb7466e74f81b3e545563cdd8f5524dae873de61d7bdfccd496af2584930d2b566b4f8d3881f8c043df92224f38cf094cfc09d92655989531524593ec6d6caec1863bdfaa79229b5020acc034cd6deeea1021c50586947b9b8e6faa83b81fbfa6133c0af5d6b07c017f7158fa94f0d206baf12dda6b68f785b773b360fd0497e16cc402d779c8d48d0fa6315536ef0660f3f4e1865f5b38ea49c7da4fd959de4e83ff3ab686f059a45c65ba2af4a6a79166aa0f496bf04d06987b6d2ea205bdb0d347718b9aeff5b61dfff344993a275b79717cd815b6ad4c0beb568c4ac9c36ff1c315ec1119a1993c4b61e6eaa0375e0aaf738ac691abd3263bf937e3").unwrap());
3551
3552                 let onion_packet_4 = ChannelManager::encrypt_failure_packet(&onion_keys[1].shared_secret[..], &onion_packet_3.data[..]);
3553                 assert_eq!(onion_packet_4.data, hex::decode("aac3200c4968f56b21f53e5e374e3a2383ad2b1b6501bbcc45abc31e59b26881b7dfadbb56ec8dae8857add94e6702fb4c3a4de22e2e669e1ed926b04447fc73034bb730f4932acd62727b75348a648a1128744657ca6a4e713b9b646c3ca66cac02cdab44dd3439890ef3aaf61708714f7375349b8da541b2548d452d84de7084bb95b3ac2345201d624d31f4d52078aa0fa05a88b4e20202bd2b86ac5b52919ea305a8949de95e935eed0319cf3cf19ebea61d76ba92532497fcdc9411d06bcd4275094d0a4a3c5d3a945e43305a5a9256e333e1f64dbca5fcd4e03a39b9012d197506e06f29339dfee3331995b21615337ae060233d39befea925cc262873e0530408e6990f1cbd233a150ef7b004ff6166c70c68d9f8c853c1abca640b8660db2921").unwrap());
3554
3555                 let onion_packet_5 = ChannelManager::encrypt_failure_packet(&onion_keys[0].shared_secret[..], &onion_packet_4.data[..]);
3556                 assert_eq!(onion_packet_5.data, hex::decode("9c5add3963fc7f6ed7f148623c84134b5647e1306419dbe2174e523fa9e2fbed3a06a19f899145610741c83ad40b7712aefaddec8c6baf7325d92ea4ca4d1df8bce517f7e54554608bf2bd8071a4f52a7a2f7ffbb1413edad81eeea5785aa9d990f2865dc23b4bc3c301a94eec4eabebca66be5cf638f693ec256aec514620cc28ee4a94bd9565bc4d4962b9d3641d4278fb319ed2b84de5b665f307a2db0f7fbb757366067d88c50f7e829138fde4f78d39b5b5802f1b92a8a820865af5cc79f9f30bc3f461c66af95d13e5e1f0381c184572a91dee1c849048a647a1158cf884064deddbf1b0b88dfe2f791428d0ba0f6fb2f04e14081f69165ae66d9297c118f0907705c9c4954a199bae0bb96fad763d690e7daa6cfda59ba7f2c8d11448b604d12d").unwrap());
3557         }
3558
3559         fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
3560                 assert!(chain.does_match_tx(tx));
3561                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3562                 chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
3563                 for i in 2..100 {
3564                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3565                         chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
3566                 }
3567         }
3568
3569         struct Node {
3570                 chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
3571                 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
3572                 chan_monitor: Arc<test_utils::TestChannelMonitor>,
3573                 node: Arc<ChannelManager>,
3574                 router: Router,
3575                 node_seed: [u8; 32],
3576                 network_payment_count: Rc<RefCell<u8>>,
3577                 network_chan_count: Rc<RefCell<u32>>,
3578         }
3579         impl Drop for Node {
3580                 fn drop(&mut self) {
3581                         if !::std::thread::panicking() {
3582                                 // Check that we processed all pending events
3583                                 assert_eq!(self.node.get_and_clear_pending_msg_events().len(), 0);
3584                                 assert_eq!(self.node.get_and_clear_pending_events().len(), 0);
3585                                 assert_eq!(self.chan_monitor.added_monitors.lock().unwrap().len(), 0);
3586                         }
3587                 }
3588         }
3589
3590         fn create_chan_between_nodes(node_a: &Node, node_b: &Node) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3591                 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001)
3592         }
3593
3594         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) {
3595                 let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat);
3596                 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
3597                 (announcement, as_update, bs_update, channel_id, tx)
3598         }
3599
3600         macro_rules! get_revoke_commit_msgs {
3601                 ($node: expr, $node_id: expr) => {
3602                         {
3603                                 let events = $node.node.get_and_clear_pending_msg_events();
3604                                 assert_eq!(events.len(), 2);
3605                                 (match events[0] {
3606                                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3607                                                 assert_eq!(*node_id, $node_id);
3608                                                 (*msg).clone()
3609                                         },
3610                                         _ => panic!("Unexpected event"),
3611                                 }, match events[1] {
3612                                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3613                                                 assert_eq!(*node_id, $node_id);
3614                                                 assert!(updates.update_add_htlcs.is_empty());
3615                                                 assert!(updates.update_fulfill_htlcs.is_empty());
3616                                                 assert!(updates.update_fail_htlcs.is_empty());
3617                                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
3618                                                 assert!(updates.update_fee.is_none());
3619                                                 updates.commitment_signed.clone()
3620                                         },
3621                                         _ => panic!("Unexpected event"),
3622                                 })
3623                         }
3624                 }
3625         }
3626
3627         macro_rules! get_event_msg {
3628                 ($node: expr, $event_type: path, $node_id: expr) => {
3629                         {
3630                                 let events = $node.node.get_and_clear_pending_msg_events();
3631                                 assert_eq!(events.len(), 1);
3632                                 match events[0] {
3633                                         $event_type { ref node_id, ref msg } => {
3634                                                 assert_eq!(*node_id, $node_id);
3635                                                 (*msg).clone()
3636                                         },
3637                                         _ => panic!("Unexpected event"),
3638                                 }
3639                         }
3640                 }
3641         }
3642
3643         macro_rules! get_htlc_update_msgs {
3644                 ($node: expr, $node_id: expr) => {
3645                         {
3646                                 let events = $node.node.get_and_clear_pending_msg_events();
3647                                 assert_eq!(events.len(), 1);
3648                                 match events[0] {
3649                                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3650                                                 assert_eq!(*node_id, $node_id);
3651                                                 (*updates).clone()
3652                                         },
3653                                         _ => panic!("Unexpected event"),
3654                                 }
3655                         }
3656                 }
3657         }
3658
3659         macro_rules! get_feerate {
3660                 ($node: expr, $channel_id: expr) => {
3661                         {
3662                                 let chan_lock = $node.node.channel_state.lock().unwrap();
3663                                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
3664                                 chan.get_feerate()
3665                         }
3666                 }
3667         }
3668
3669
3670         fn create_chan_between_nodes_with_value_init(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> Transaction {
3671                 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
3672                 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();
3673                 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();
3674
3675                 let chan_id = *node_a.network_chan_count.borrow();
3676                 let tx;
3677                 let funding_output;
3678
3679                 let events_2 = node_a.node.get_and_clear_pending_events();
3680                 assert_eq!(events_2.len(), 1);
3681                 match events_2[0] {
3682                         Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
3683                                 assert_eq!(*channel_value_satoshis, channel_value);
3684                                 assert_eq!(user_channel_id, 42);
3685
3686                                 tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
3687                                         value: *channel_value_satoshis, script_pubkey: output_script.clone(),
3688                                 }]};
3689                                 funding_output = OutPoint::new(tx.txid(), 0);
3690
3691                                 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
3692                                 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3693                                 assert_eq!(added_monitors.len(), 1);
3694                                 assert_eq!(added_monitors[0].0, funding_output);
3695                                 added_monitors.clear();
3696                         },
3697                         _ => panic!("Unexpected event"),
3698                 }
3699
3700                 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();
3701                 {
3702                         let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
3703                         assert_eq!(added_monitors.len(), 1);
3704                         assert_eq!(added_monitors[0].0, funding_output);
3705                         added_monitors.clear();
3706                 }
3707
3708                 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();
3709                 {
3710                         let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3711                         assert_eq!(added_monitors.len(), 1);
3712                         assert_eq!(added_monitors[0].0, funding_output);
3713                         added_monitors.clear();
3714                 }
3715
3716                 let events_4 = node_a.node.get_and_clear_pending_events();
3717                 assert_eq!(events_4.len(), 1);
3718                 match events_4[0] {
3719                         Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
3720                                 assert_eq!(user_channel_id, 42);
3721                                 assert_eq!(*funding_txo, funding_output);
3722                         },
3723                         _ => panic!("Unexpected event"),
3724                 };
3725
3726                 tx
3727         }
3728
3729         fn create_chan_between_nodes_with_value_confirm(node_a: &Node, node_b: &Node, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
3730                 confirm_transaction(&node_b.chain_monitor, &tx, tx.version);
3731                 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();
3732
3733                 let channel_id;
3734
3735                 confirm_transaction(&node_a.chain_monitor, &tx, tx.version);
3736                 let events_6 = node_a.node.get_and_clear_pending_msg_events();
3737                 assert_eq!(events_6.len(), 2);
3738                 ((match events_6[0] {
3739                         MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3740                                 channel_id = msg.channel_id.clone();
3741                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
3742                                 msg.clone()
3743                         },
3744                         _ => panic!("Unexpected event"),
3745                 }, match events_6[1] {
3746                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3747                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
3748                                 msg.clone()
3749                         },
3750                         _ => panic!("Unexpected event"),
3751                 }), channel_id)
3752         }
3753
3754         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) {
3755                 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat);
3756                 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
3757                 (msgs, chan_id, tx)
3758         }
3759
3760         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) {
3761                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0).unwrap();
3762                 let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
3763                 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1).unwrap();
3764
3765                 let events_7 = node_b.node.get_and_clear_pending_msg_events();
3766                 assert_eq!(events_7.len(), 1);
3767                 let (announcement, bs_update) = match events_7[0] {
3768                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3769                                 (msg, update_msg)
3770                         },
3771                         _ => panic!("Unexpected event"),
3772                 };
3773
3774                 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs).unwrap();
3775                 let events_8 = node_a.node.get_and_clear_pending_msg_events();
3776                 assert_eq!(events_8.len(), 1);
3777                 let as_update = match events_8[0] {
3778                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3779                                 assert!(*announcement == *msg);
3780                                 assert_eq!(update_msg.contents.short_channel_id, announcement.contents.short_channel_id);
3781                                 assert_eq!(update_msg.contents.short_channel_id, bs_update.contents.short_channel_id);
3782                                 update_msg
3783                         },
3784                         _ => panic!("Unexpected event"),
3785                 };
3786
3787                 *node_a.network_chan_count.borrow_mut() += 1;
3788
3789                 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
3790         }
3791
3792         fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3793                 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001)
3794         }
3795
3796         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) {
3797                 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat);
3798                 for node in nodes {
3799                         assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
3800                         node.router.handle_channel_update(&chan_announcement.1).unwrap();
3801                         node.router.handle_channel_update(&chan_announcement.2).unwrap();
3802                 }
3803                 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
3804         }
3805
3806         macro_rules! check_spends {
3807                 ($tx: expr, $spends_tx: expr) => {
3808                         {
3809                                 let mut funding_tx_map = HashMap::new();
3810                                 let spends_tx = $spends_tx;
3811                                 funding_tx_map.insert(spends_tx.txid(), spends_tx);
3812                                 $tx.verify(&funding_tx_map).unwrap();
3813                         }
3814                 }
3815         }
3816
3817         macro_rules! get_closing_signed_broadcast {
3818                 ($node: expr, $dest_pubkey: expr) => {
3819                         {
3820                                 let events = $node.get_and_clear_pending_msg_events();
3821                                 assert!(events.len() == 1 || events.len() == 2);
3822                                 (match events[events.len() - 1] {
3823                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
3824                                                 assert_eq!(msg.contents.flags & 2, 2);
3825                                                 msg.clone()
3826                                         },
3827                                         _ => panic!("Unexpected event"),
3828                                 }, if events.len() == 2 {
3829                                         match events[0] {
3830                                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3831                                                         assert_eq!(*node_id, $dest_pubkey);
3832                                                         Some(msg.clone())
3833                                                 },
3834                                                 _ => panic!("Unexpected event"),
3835                                         }
3836                                 } else { None })
3837                         }
3838                 }
3839         }
3840
3841         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) {
3842                 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) };
3843                 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
3844                 let (tx_a, tx_b);
3845
3846                 node_a.close_channel(channel_id).unwrap();
3847                 node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id())).unwrap();
3848
3849                 let events_1 = node_b.get_and_clear_pending_msg_events();
3850                 assert!(events_1.len() >= 1);
3851                 let shutdown_b = match events_1[0] {
3852                         MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
3853                                 assert_eq!(node_id, &node_a.get_our_node_id());
3854                                 msg.clone()
3855                         },
3856                         _ => panic!("Unexpected event"),
3857                 };
3858
3859                 let closing_signed_b = if !close_inbound_first {
3860                         assert_eq!(events_1.len(), 1);
3861                         None
3862                 } else {
3863                         Some(match events_1[1] {
3864                                 MessageSendEvent::SendClosingSigned { 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
3872                 node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b).unwrap();
3873                 let (as_update, bs_update) = if close_inbound_first {
3874                         assert!(node_a.get_and_clear_pending_msg_events().is_empty());
3875                         node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3876                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3877                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3878                         let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3879
3880                         node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
3881                         let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3882                         assert!(none_b.is_none());
3883                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3884                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3885                         (as_update, bs_update)
3886                 } else {
3887                         let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
3888
3889                         node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a).unwrap();
3890                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3891                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3892                         let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3893
3894                         node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3895                         let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3896                         assert!(none_a.is_none());
3897                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3898                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3899                         (as_update, bs_update)
3900                 };
3901                 assert_eq!(tx_a, tx_b);
3902                 check_spends!(tx_a, funding_tx);
3903
3904                 (as_update, bs_update, tx_a)
3905         }
3906
3907         struct SendEvent {
3908                 node_id: PublicKey,
3909                 msgs: Vec<msgs::UpdateAddHTLC>,
3910                 commitment_msg: msgs::CommitmentSigned,
3911         }
3912         impl SendEvent {
3913                 fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
3914                         assert!(updates.update_fulfill_htlcs.is_empty());
3915                         assert!(updates.update_fail_htlcs.is_empty());
3916                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3917                         assert!(updates.update_fee.is_none());
3918                         SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
3919                 }
3920
3921                 fn from_event(event: MessageSendEvent) -> SendEvent {
3922                         match event {
3923                                 MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
3924                                 _ => panic!("Unexpected event type!"),
3925                         }
3926                 }
3927
3928                 fn from_node(node: &Node) -> SendEvent {
3929                         let mut events = node.node.get_and_clear_pending_msg_events();
3930                         assert_eq!(events.len(), 1);
3931                         SendEvent::from_event(events.pop().unwrap())
3932                 }
3933         }
3934
3935         macro_rules! check_added_monitors {
3936                 ($node: expr, $count: expr) => {
3937                         {
3938                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
3939                                 assert_eq!(added_monitors.len(), $count);
3940                                 added_monitors.clear();
3941                         }
3942                 }
3943         }
3944
3945         macro_rules! commitment_signed_dance {
3946                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
3947                         {
3948                                 check_added_monitors!($node_a, 0);
3949                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3950                                 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3951                                 check_added_monitors!($node_a, 1);
3952                                 commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
3953                         }
3954                 };
3955                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
3956                         {
3957                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
3958                                 check_added_monitors!($node_b, 0);
3959                                 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3960                                 $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
3961                                 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3962                                 check_added_monitors!($node_b, 1);
3963                                 $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed).unwrap();
3964                                 let (bs_revoke_and_ack, extra_msg_option) = {
3965                                         let events = $node_b.node.get_and_clear_pending_msg_events();
3966                                         assert!(events.len() <= 2);
3967                                         (match events[0] {
3968                                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3969                                                         assert_eq!(*node_id, $node_a.node.get_our_node_id());
3970                                                         (*msg).clone()
3971                                                 },
3972                                                 _ => panic!("Unexpected event"),
3973                                         }, events.get(1).map(|e| e.clone()))
3974                                 };
3975                                 check_added_monitors!($node_b, 1);
3976                                 if $fail_backwards {
3977                                         assert!($node_a.node.get_and_clear_pending_events().is_empty());
3978                                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3979                                 }
3980                                 (extra_msg_option, bs_revoke_and_ack)
3981                         }
3982                 };
3983                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
3984                         {
3985                                 check_added_monitors!($node_a, 0);
3986                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3987                                 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3988                                 check_added_monitors!($node_a, 1);
3989                                 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
3990                                 assert!(extra_msg_option.is_none());
3991                                 bs_revoke_and_ack
3992                         }
3993                 };
3994                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
3995                         {
3996                                 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
3997                                 $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
3998                                 {
3999                                         let mut added_monitors = $node_a.chan_monitor.added_monitors.lock().unwrap();
4000                                         if $fail_backwards {
4001                                                 assert_eq!(added_monitors.len(), 2);
4002                                                 assert!(added_monitors[0].0 != added_monitors[1].0);
4003                                         } else {
4004                                                 assert_eq!(added_monitors.len(), 1);
4005                                         }
4006                                         added_monitors.clear();
4007                                 }
4008                                 extra_msg_option
4009                         }
4010                 };
4011                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
4012                         {
4013                                 assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
4014                         }
4015                 };
4016                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
4017                         {
4018                                 commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
4019                                 if $fail_backwards {
4020                                         let channel_state = $node_a.node.channel_state.lock().unwrap();
4021                                         assert_eq!(channel_state.pending_msg_events.len(), 1);
4022                                         if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
4023                                                 assert_ne!(*node_id, $node_b.node.get_our_node_id());
4024                                         } else { panic!("Unexpected event"); }
4025                                 } else {
4026                                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
4027                                 }
4028                         }
4029                 }
4030         }
4031
4032         macro_rules! get_payment_preimage_hash {
4033                 ($node: expr) => {
4034                         {
4035                                 let payment_preimage = PaymentPreimage([*$node.network_payment_count.borrow(); 32]);
4036                                 *$node.network_payment_count.borrow_mut() += 1;
4037                                 let mut payment_hash = PaymentHash([0; 32]);
4038                                 let mut sha = Sha256::new();
4039                                 sha.input(&payment_preimage.0[..]);
4040                                 sha.result(&mut payment_hash.0[..]);
4041                                 (payment_preimage, payment_hash)
4042                         }
4043                 }
4044         }
4045
4046         fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
4047                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4048
4049                 let mut payment_event = {
4050                         origin_node.node.send_payment(route, our_payment_hash).unwrap();
4051                         check_added_monitors!(origin_node, 1);
4052
4053                         let mut events = origin_node.node.get_and_clear_pending_msg_events();
4054                         assert_eq!(events.len(), 1);
4055                         SendEvent::from_event(events.remove(0))
4056                 };
4057                 let mut prev_node = origin_node;
4058
4059                 for (idx, &node) in expected_route.iter().enumerate() {
4060                         assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
4061
4062                         node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4063                         check_added_monitors!(node, 0);
4064                         commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
4065
4066                         let events_1 = node.node.get_and_clear_pending_events();
4067                         assert_eq!(events_1.len(), 1);
4068                         match events_1[0] {
4069                                 Event::PendingHTLCsForwardable { .. } => { },
4070                                 _ => panic!("Unexpected event"),
4071                         };
4072
4073                         node.node.channel_state.lock().unwrap().next_forward = Instant::now();
4074                         node.node.process_pending_htlc_forwards();
4075
4076                         if idx == expected_route.len() - 1 {
4077                                 let events_2 = node.node.get_and_clear_pending_events();
4078                                 assert_eq!(events_2.len(), 1);
4079                                 match events_2[0] {
4080                                         Event::PaymentReceived { ref payment_hash, amt } => {
4081                                                 assert_eq!(our_payment_hash, *payment_hash);
4082                                                 assert_eq!(amt, recv_value);
4083                                         },
4084                                         _ => panic!("Unexpected event"),
4085                                 }
4086                         } else {
4087                                 let mut events_2 = node.node.get_and_clear_pending_msg_events();
4088                                 assert_eq!(events_2.len(), 1);
4089                                 check_added_monitors!(node, 1);
4090                                 payment_event = SendEvent::from_event(events_2.remove(0));
4091                                 assert_eq!(payment_event.msgs.len(), 1);
4092                         }
4093
4094                         prev_node = node;
4095                 }
4096
4097                 (our_payment_preimage, our_payment_hash)
4098         }
4099
4100         fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: PaymentPreimage) {
4101                 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
4102                 check_added_monitors!(expected_route.last().unwrap(), 1);
4103
4104                 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
4105                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4106                 macro_rules! get_next_msgs {
4107                         ($node: expr) => {
4108                                 {
4109                                         let events = $node.node.get_and_clear_pending_msg_events();
4110                                         assert_eq!(events.len(), 1);
4111                                         match events[0] {
4112                                                 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 } } => {
4113                                                         assert!(update_add_htlcs.is_empty());
4114                                                         assert_eq!(update_fulfill_htlcs.len(), 1);
4115                                                         assert!(update_fail_htlcs.is_empty());
4116                                                         assert!(update_fail_malformed_htlcs.is_empty());
4117                                                         assert!(update_fee.is_none());
4118                                                         expected_next_node = node_id.clone();
4119                                                         Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()))
4120                                                 },
4121                                                 _ => panic!("Unexpected event"),
4122                                         }
4123                                 }
4124                         }
4125                 }
4126
4127                 macro_rules! last_update_fulfill_dance {
4128                         ($node: expr, $prev_node: expr) => {
4129                                 {
4130                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4131                                         check_added_monitors!($node, 0);
4132                                         assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4133                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4134                                 }
4135                         }
4136                 }
4137                 macro_rules! mid_update_fulfill_dance {
4138                         ($node: expr, $prev_node: expr, $new_msgs: expr) => {
4139                                 {
4140                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4141                                         check_added_monitors!($node, 1);
4142                                         let new_next_msgs = if $new_msgs {
4143                                                 get_next_msgs!($node)
4144                                         } else {
4145                                                 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4146                                                 None
4147                                         };
4148                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4149                                         next_msgs = new_next_msgs;
4150                                 }
4151                         }
4152                 }
4153
4154                 let mut prev_node = expected_route.last().unwrap();
4155                 for (idx, node) in expected_route.iter().rev().enumerate() {
4156                         assert_eq!(expected_next_node, node.node.get_our_node_id());
4157                         let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
4158                         if next_msgs.is_some() {
4159                                 mid_update_fulfill_dance!(node, prev_node, update_next_msgs);
4160                         } else if update_next_msgs {
4161                                 next_msgs = get_next_msgs!(node);
4162                         } else {
4163                                 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
4164                         }
4165                         if !skip_last && idx == expected_route.len() - 1 {
4166                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4167                         }
4168
4169                         prev_node = node;
4170                 }
4171
4172                 if !skip_last {
4173                         last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
4174                         let events = origin_node.node.get_and_clear_pending_events();
4175                         assert_eq!(events.len(), 1);
4176                         match events[0] {
4177                                 Event::PaymentSent { payment_preimage } => {
4178                                         assert_eq!(payment_preimage, our_payment_preimage);
4179                                 },
4180                                 _ => panic!("Unexpected event"),
4181                         }
4182                 }
4183         }
4184
4185         fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: PaymentPreimage) {
4186                 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage);
4187         }
4188
4189         const TEST_FINAL_CLTV: u32 = 32;
4190
4191         fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
4192                 let route = origin_node.router.get_route(&expected_route.last().unwrap().node.get_our_node_id(), None, &Vec::new(), recv_value, TEST_FINAL_CLTV).unwrap();
4193                 assert_eq!(route.hops.len(), expected_route.len());
4194                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4195                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
4196                 }
4197
4198                 send_along_route(origin_node, route, expected_route, recv_value)
4199         }
4200
4201         fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
4202                 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();
4203                 assert_eq!(route.hops.len(), expected_route.len());
4204                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4205                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
4206                 }
4207
4208                 let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4209
4210                 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
4211                 match err {
4212                         APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
4213                         _ => panic!("Unknown error variants"),
4214                 };
4215         }
4216
4217         fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
4218                 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
4219                 claim_payment(&origin, expected_route, our_payment_preimage);
4220         }
4221
4222         fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: PaymentHash) {
4223                 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash, PaymentFailReason::PreimageUnknown));
4224                 check_added_monitors!(expected_route.last().unwrap(), 1);
4225
4226                 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
4227                 macro_rules! update_fail_dance {
4228                         ($node: expr, $prev_node: expr, $last_node: expr) => {
4229                                 {
4230                                         $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4231                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
4232                                 }
4233                         }
4234                 }
4235
4236                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4237                 let mut prev_node = expected_route.last().unwrap();
4238                 for (idx, node) in expected_route.iter().rev().enumerate() {
4239                         assert_eq!(expected_next_node, node.node.get_our_node_id());
4240                         if next_msgs.is_some() {
4241                                 // We may be the "last node" for the purpose of the commitment dance if we're
4242                                 // skipping the last node (implying it is disconnected) and we're the
4243                                 // second-to-last node!
4244                                 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
4245                         }
4246
4247                         let events = node.node.get_and_clear_pending_msg_events();
4248                         if !skip_last || idx != expected_route.len() - 1 {
4249                                 assert_eq!(events.len(), 1);
4250                                 match events[0] {
4251                                         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 } } => {
4252                                                 assert!(update_add_htlcs.is_empty());
4253                                                 assert!(update_fulfill_htlcs.is_empty());
4254                                                 assert_eq!(update_fail_htlcs.len(), 1);
4255                                                 assert!(update_fail_malformed_htlcs.is_empty());
4256                                                 assert!(update_fee.is_none());
4257                                                 expected_next_node = node_id.clone();
4258                                                 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
4259                                         },
4260                                         _ => panic!("Unexpected event"),
4261                                 }
4262                         } else {
4263                                 assert!(events.is_empty());
4264                         }
4265                         if !skip_last && idx == expected_route.len() - 1 {
4266                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4267                         }
4268
4269                         prev_node = node;
4270                 }
4271
4272                 if !skip_last {
4273                         update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
4274
4275                         let events = origin_node.node.get_and_clear_pending_events();
4276                         assert_eq!(events.len(), 1);
4277                         match events[0] {
4278                                 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
4279                                         assert_eq!(payment_hash, our_payment_hash);
4280                                         assert!(rejected_by_dest);
4281                                 },
4282                                 _ => panic!("Unexpected event"),
4283                         }
4284                 }
4285         }
4286
4287         fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: PaymentHash) {
4288                 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
4289         }
4290
4291         fn create_network(node_count: usize) -> Vec<Node> {
4292                 let mut nodes = Vec::new();
4293                 let mut rng = thread_rng();
4294                 let secp_ctx = Secp256k1::new();
4295
4296                 let chan_count = Rc::new(RefCell::new(0));
4297                 let payment_count = Rc::new(RefCell::new(0));
4298
4299                 for i in 0..node_count {
4300                         let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
4301                         let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
4302                         let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
4303                         let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
4304                         let mut seed = [0; 32];
4305                         rng.fill_bytes(&mut seed);
4306                         let keys_manager = Arc::new(keysinterface::KeysManager::new(&seed, Network::Testnet, Arc::clone(&logger)));
4307                         let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone()));
4308                         let mut config = UserConfig::new();
4309                         config.channel_options.announced_channel = true;
4310                         config.channel_limits.force_announced_channel_preference = false;
4311                         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();
4312                         let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), chain_monitor.clone(), Arc::clone(&logger));
4313                         nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router, node_seed: seed,
4314                                 network_payment_count: payment_count.clone(),
4315                                 network_chan_count: chan_count.clone(),
4316                         });
4317                 }
4318
4319                 nodes
4320         }
4321
4322         #[test]
4323         fn test_async_inbound_update_fee() {
4324                 let mut nodes = create_network(2);
4325                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4326                 let channel_id = chan.2;
4327
4328                 // balancing
4329                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4330
4331                 // A                                        B
4332                 // update_fee                            ->
4333                 // send (1) commitment_signed            -.
4334                 //                                       <- update_add_htlc/commitment_signed
4335                 // send (2) RAA (awaiting remote revoke) -.
4336                 // (1) commitment_signed is delivered    ->
4337                 //                                       .- send (3) RAA (awaiting remote revoke)
4338                 // (2) RAA is delivered                  ->
4339                 //                                       .- send (4) commitment_signed
4340                 //                                       <- (3) RAA is delivered
4341                 // send (5) commitment_signed            -.
4342                 //                                       <- (4) commitment_signed is delivered
4343                 // send (6) RAA                          -.
4344                 // (5) commitment_signed is delivered    ->
4345                 //                                       <- RAA
4346                 // (6) RAA is delivered                  ->
4347
4348                 // First nodes[0] generates an update_fee
4349                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4350                 check_added_monitors!(nodes[0], 1);
4351
4352                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4353                 assert_eq!(events_0.len(), 1);
4354                 let (update_msg, commitment_signed) = match events_0[0] { // (1)
4355                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4356                                 (update_fee.as_ref(), commitment_signed)
4357                         },
4358                         _ => panic!("Unexpected event"),
4359                 };
4360
4361                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4362
4363                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4364                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4365                 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();
4366                 check_added_monitors!(nodes[1], 1);
4367
4368                 let payment_event = {
4369                         let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4370                         assert_eq!(events_1.len(), 1);
4371                         SendEvent::from_event(events_1.remove(0))
4372                 };
4373                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4374                 assert_eq!(payment_event.msgs.len(), 1);
4375
4376                 // ...now when the messages get delivered everyone should be happy
4377                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4378                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4379                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4380                 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4381                 check_added_monitors!(nodes[0], 1);
4382
4383                 // deliver(1), generate (3):
4384                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4385                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4386                 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
4387                 check_added_monitors!(nodes[1], 1);
4388
4389                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap(); // deliver (2)
4390                 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4391                 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
4392                 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
4393                 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
4394                 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
4395                 assert!(bs_update.update_fee.is_none()); // (4)
4396                 check_added_monitors!(nodes[1], 1);
4397
4398                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap(); // deliver (3)
4399                 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4400                 assert!(as_update.update_add_htlcs.is_empty()); // (5)
4401                 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
4402                 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
4403                 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
4404                 assert!(as_update.update_fee.is_none()); // (5)
4405                 check_added_monitors!(nodes[0], 1);
4406
4407                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed).unwrap(); // deliver (4)
4408                 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4409                 // only (6) so get_event_msg's assert(len == 1) passes
4410                 check_added_monitors!(nodes[0], 1);
4411
4412                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed).unwrap(); // deliver (5)
4413                 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4414                 check_added_monitors!(nodes[1], 1);
4415
4416                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4417                 check_added_monitors!(nodes[0], 1);
4418
4419                 let events_2 = nodes[0].node.get_and_clear_pending_events();
4420                 assert_eq!(events_2.len(), 1);
4421                 match events_2[0] {
4422                         Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
4423                         _ => panic!("Unexpected event"),
4424                 }
4425
4426                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap(); // deliver (6)
4427                 check_added_monitors!(nodes[1], 1);
4428         }
4429
4430         #[test]
4431         fn test_update_fee_unordered_raa() {
4432                 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
4433                 // crash in an earlier version of the update_fee patch)
4434                 let mut nodes = create_network(2);
4435                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4436                 let channel_id = chan.2;
4437
4438                 // balancing
4439                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4440
4441                 // First nodes[0] generates an update_fee
4442                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4443                 check_added_monitors!(nodes[0], 1);
4444
4445                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4446                 assert_eq!(events_0.len(), 1);
4447                 let update_msg = match events_0[0] { // (1)
4448                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
4449                                 update_fee.as_ref()
4450                         },
4451                         _ => panic!("Unexpected event"),
4452                 };
4453
4454                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4455
4456                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4457                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4458                 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();
4459                 check_added_monitors!(nodes[1], 1);
4460
4461                 let payment_event = {
4462                         let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4463                         assert_eq!(events_1.len(), 1);
4464                         SendEvent::from_event(events_1.remove(0))
4465                 };
4466                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4467                 assert_eq!(payment_event.msgs.len(), 1);
4468
4469                 // ...now when the messages get delivered everyone should be happy
4470                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4471                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4472                 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4473                 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4474                 check_added_monitors!(nodes[0], 1);
4475
4476                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap(); // deliver (2)
4477                 check_added_monitors!(nodes[1], 1);
4478
4479                 // We can't continue, sadly, because our (1) now has a bogus signature
4480         }
4481
4482         #[test]
4483         fn test_multi_flight_update_fee() {
4484                 let nodes = create_network(2);
4485                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4486                 let channel_id = chan.2;
4487
4488                 // A                                        B
4489                 // update_fee/commitment_signed          ->
4490                 //                                       .- send (1) RAA and (2) commitment_signed
4491                 // update_fee (never committed)          ->
4492                 // (3) update_fee                        ->
4493                 // We have to manually generate the above update_fee, it is allowed by the protocol but we
4494                 // don't track which updates correspond to which revoke_and_ack responses so we're in
4495                 // AwaitingRAA mode and will not generate the update_fee yet.
4496                 //                                       <- (1) RAA delivered
4497                 // (3) is generated and send (4) CS      -.
4498                 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
4499                 // know the per_commitment_point to use for it.
4500                 //                                       <- (2) commitment_signed delivered
4501                 // revoke_and_ack                        ->
4502                 //                                          B should send no response here
4503                 // (4) commitment_signed delivered       ->
4504                 //                                       <- RAA/commitment_signed delivered
4505                 // revoke_and_ack                        ->
4506
4507                 // First nodes[0] generates an update_fee
4508                 let initial_feerate = get_feerate!(nodes[0], channel_id);
4509                 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
4510                 check_added_monitors!(nodes[0], 1);
4511
4512                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4513                 assert_eq!(events_0.len(), 1);
4514                 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
4515                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4516                                 (update_fee.as_ref().unwrap(), commitment_signed)
4517                         },
4518                         _ => panic!("Unexpected event"),
4519                 };
4520
4521                 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
4522                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1).unwrap();
4523                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1).unwrap();
4524                 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4525                 check_added_monitors!(nodes[1], 1);
4526
4527                 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
4528                 // transaction:
4529                 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
4530                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4531                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4532
4533                 // Create the (3) update_fee message that nodes[0] will generate before it does...
4534                 let mut update_msg_2 = msgs::UpdateFee {
4535                         channel_id: update_msg_1.channel_id.clone(),
4536                         feerate_per_kw: (initial_feerate + 30) as u32,
4537                 };
4538
4539                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4540
4541                 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
4542                 // Deliver (3)
4543                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4544
4545                 // Deliver (1), generating (3) and (4)
4546                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap();
4547                 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4548                 check_added_monitors!(nodes[0], 1);
4549                 assert!(as_second_update.update_add_htlcs.is_empty());
4550                 assert!(as_second_update.update_fulfill_htlcs.is_empty());
4551                 assert!(as_second_update.update_fail_htlcs.is_empty());
4552                 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
4553                 // Check that the update_fee newly generated matches what we delivered:
4554                 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
4555                 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
4556
4557                 // Deliver (2) commitment_signed
4558                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
4559                 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4560                 check_added_monitors!(nodes[0], 1);
4561                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4562
4563                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap();
4564                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4565                 check_added_monitors!(nodes[1], 1);
4566
4567                 // Delever (4)
4568                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed).unwrap();
4569                 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4570                 check_added_monitors!(nodes[1], 1);
4571
4572                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4573                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4574                 check_added_monitors!(nodes[0], 1);
4575
4576                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment).unwrap();
4577                 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4578                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4579                 check_added_monitors!(nodes[0], 1);
4580
4581                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap();
4582                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4583                 check_added_monitors!(nodes[1], 1);
4584         }
4585
4586         #[test]
4587         fn test_update_fee_vanilla() {
4588                 let nodes = create_network(2);
4589                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4590                 let channel_id = chan.2;
4591
4592                 let feerate = get_feerate!(nodes[0], channel_id);
4593                 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
4594                 check_added_monitors!(nodes[0], 1);
4595
4596                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4597                 assert_eq!(events_0.len(), 1);
4598                 let (update_msg, commitment_signed) = match events_0[0] {
4599                                 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 } } => {
4600                                 (update_fee.as_ref(), commitment_signed)
4601                         },
4602                         _ => panic!("Unexpected event"),
4603                 };
4604                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4605
4606                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4607                 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4608                 check_added_monitors!(nodes[1], 1);
4609
4610                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4611                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4612                 check_added_monitors!(nodes[0], 1);
4613
4614                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4615                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4616                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4617                 check_added_monitors!(nodes[0], 1);
4618
4619                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4620                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4621                 check_added_monitors!(nodes[1], 1);
4622         }
4623
4624         #[test]
4625         fn test_update_fee_that_funder_cannot_afford() {
4626                 let nodes = create_network(2);
4627                 let channel_value = 1888;
4628                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000);
4629                 let channel_id = chan.2;
4630
4631                 let feerate = 260;
4632                 nodes[0].node.update_fee(channel_id, feerate).unwrap();
4633                 check_added_monitors!(nodes[0], 1);
4634                 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4635
4636                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap()).unwrap();
4637
4638                 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
4639
4640                 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
4641                 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
4642                 {
4643                         let chan_lock = nodes[1].node.channel_state.lock().unwrap();
4644                         let chan = chan_lock.by_id.get(&channel_id).unwrap();
4645
4646                         //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
4647                         let num_htlcs = chan.last_local_commitment_txn[0].output.len() - 2;
4648                         let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
4649                         let mut actual_fee = chan.last_local_commitment_txn[0].output.iter().fold(0, |acc, output| acc + output.value);
4650                         actual_fee = channel_value - actual_fee;
4651                         assert_eq!(total_fee, actual_fee);
4652                 } //drop the mutex
4653
4654                 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
4655                 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
4656                 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
4657                 check_added_monitors!(nodes[0], 1);
4658
4659                 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4660
4661                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap()).unwrap();
4662
4663                 //While producing the commitment_signed response after handling a received update_fee request the
4664                 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
4665                 //Should produce and error.
4666                 let err = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed).unwrap_err();
4667
4668                 assert!(match err.err {
4669                         "Funding remote cannot afford proposed new fee" => true,
4670                         _ => false,
4671                 });
4672
4673                 //clear the message we could not handle
4674                 nodes[1].node.get_and_clear_pending_msg_events();
4675         }
4676
4677         #[test]
4678         fn test_update_fee_with_fundee_update_add_htlc() {
4679                 let mut nodes = create_network(2);
4680                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4681                 let channel_id = chan.2;
4682
4683                 // balancing
4684                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4685
4686                 let feerate = get_feerate!(nodes[0], channel_id);
4687                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4688                 check_added_monitors!(nodes[0], 1);
4689
4690                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4691                 assert_eq!(events_0.len(), 1);
4692                 let (update_msg, commitment_signed) = match events_0[0] {
4693                                 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 } } => {
4694                                 (update_fee.as_ref(), commitment_signed)
4695                         },
4696                         _ => panic!("Unexpected event"),
4697                 };
4698                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4699                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4700                 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4701                 check_added_monitors!(nodes[1], 1);
4702
4703                 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
4704
4705                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
4706
4707                 // nothing happens since node[1] is in AwaitingRemoteRevoke
4708                 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
4709                 {
4710                         let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
4711                         assert_eq!(added_monitors.len(), 0);
4712                         added_monitors.clear();
4713                 }
4714                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4715                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4716                 // node[1] has nothing to do
4717
4718                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4719                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4720                 check_added_monitors!(nodes[0], 1);
4721
4722                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4723                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4724                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4725                 check_added_monitors!(nodes[0], 1);
4726                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4727                 check_added_monitors!(nodes[1], 1);
4728                 // AwaitingRemoteRevoke ends here
4729
4730                 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4731                 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
4732                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
4733                 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
4734                 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
4735                 assert_eq!(commitment_update.update_fee.is_none(), true);
4736
4737                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]).unwrap();
4738                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4739                 check_added_monitors!(nodes[0], 1);
4740                 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4741
4742                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke).unwrap();
4743                 check_added_monitors!(nodes[1], 1);
4744                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4745
4746                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed).unwrap();
4747                 check_added_monitors!(nodes[1], 1);
4748                 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4749                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4750
4751                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke).unwrap();
4752                 check_added_monitors!(nodes[0], 1);
4753                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4754
4755                 let events = nodes[0].node.get_and_clear_pending_events();
4756                 assert_eq!(events.len(), 1);
4757                 match events[0] {
4758                         Event::PendingHTLCsForwardable { .. } => { },
4759                         _ => panic!("Unexpected event"),
4760                 };
4761                 nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
4762                 nodes[0].node.process_pending_htlc_forwards();
4763
4764                 let events = nodes[0].node.get_and_clear_pending_events();
4765                 assert_eq!(events.len(), 1);
4766                 match events[0] {
4767                         Event::PaymentReceived { .. } => { },
4768                         _ => panic!("Unexpected event"),
4769                 };
4770
4771                 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
4772
4773                 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
4774                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
4775                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4776         }
4777
4778         #[test]
4779         fn test_update_fee() {
4780                 let nodes = create_network(2);
4781                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4782                 let channel_id = chan.2;
4783
4784                 // A                                        B
4785                 // (1) update_fee/commitment_signed      ->
4786                 //                                       <- (2) revoke_and_ack
4787                 //                                       .- send (3) commitment_signed
4788                 // (4) update_fee/commitment_signed      ->
4789                 //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
4790                 //                                       <- (3) commitment_signed delivered
4791                 // send (6) revoke_and_ack               -.
4792                 //                                       <- (5) deliver revoke_and_ack
4793                 // (6) deliver revoke_and_ack            ->
4794                 //                                       .- send (7) commitment_signed in response to (4)
4795                 //                                       <- (7) deliver commitment_signed
4796                 // revoke_and_ack                        ->
4797
4798                 // Create and deliver (1)...
4799                 let feerate = get_feerate!(nodes[0], channel_id);
4800                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4801                 check_added_monitors!(nodes[0], 1);
4802
4803                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4804                 assert_eq!(events_0.len(), 1);
4805                 let (update_msg, commitment_signed) = match events_0[0] {
4806                                 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 } } => {
4807                                 (update_fee.as_ref(), commitment_signed)
4808                         },
4809                         _ => panic!("Unexpected event"),
4810                 };
4811                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4812
4813                 // Generate (2) and (3):
4814                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4815                 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4816                 check_added_monitors!(nodes[1], 1);
4817
4818                 // Deliver (2):
4819                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4820                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4821                 check_added_monitors!(nodes[0], 1);
4822
4823                 // Create and deliver (4)...
4824                 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
4825                 check_added_monitors!(nodes[0], 1);
4826                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4827                 assert_eq!(events_0.len(), 1);
4828                 let (update_msg, commitment_signed) = match events_0[0] {
4829                                 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 } } => {
4830                                 (update_fee.as_ref(), commitment_signed)
4831                         },
4832                         _ => panic!("Unexpected event"),
4833                 };
4834
4835                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4836                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4837                 check_added_monitors!(nodes[1], 1);
4838                 // ... creating (5)
4839                 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4840                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4841
4842                 // Handle (3), creating (6):
4843                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0).unwrap();
4844                 check_added_monitors!(nodes[0], 1);
4845                 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4846                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4847
4848                 // Deliver (5):
4849                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4850                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4851                 check_added_monitors!(nodes[0], 1);
4852
4853                 // Deliver (6), creating (7):
4854                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0).unwrap();
4855                 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4856                 assert!(commitment_update.update_add_htlcs.is_empty());
4857                 assert!(commitment_update.update_fulfill_htlcs.is_empty());
4858                 assert!(commitment_update.update_fail_htlcs.is_empty());
4859                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
4860                 assert!(commitment_update.update_fee.is_none());
4861                 check_added_monitors!(nodes[1], 1);
4862
4863                 // Deliver (7)
4864                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4865                 check_added_monitors!(nodes[0], 1);
4866                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4867                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4868
4869                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4870                 check_added_monitors!(nodes[1], 1);
4871                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4872
4873                 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
4874                 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
4875                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4876         }
4877
4878         #[test]
4879         fn pre_funding_lock_shutdown_test() {
4880                 // Test sending a shutdown prior to funding_locked after funding generation
4881                 let nodes = create_network(2);
4882                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0);
4883                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4884                 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4885                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4886
4887                 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
4888                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4889                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4890                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4891                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4892
4893                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4894                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4895                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4896                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4897                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4898                 assert!(node_0_none.is_none());
4899
4900                 assert!(nodes[0].node.list_channels().is_empty());
4901                 assert!(nodes[1].node.list_channels().is_empty());
4902         }
4903
4904         #[test]
4905         fn updates_shutdown_wait() {
4906                 // Test sending a shutdown with outstanding updates pending
4907                 let mut nodes = create_network(3);
4908                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4909                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4910                 let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4911                 let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4912
4913                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
4914
4915                 nodes[0].node.close_channel(&chan_1.2).unwrap();
4916                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4917                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4918                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4919                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4920
4921                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4922                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4923
4924                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4925                 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route_1, payment_hash) {}
4926                 else { panic!("New sends should fail!") };
4927                 if let Err(APIError::ChannelUnavailable {..}) = nodes[1].node.send_payment(route_2, payment_hash) {}
4928                 else { panic!("New sends should fail!") };
4929
4930                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
4931                 check_added_monitors!(nodes[2], 1);
4932                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4933                 assert!(updates.update_add_htlcs.is_empty());
4934                 assert!(updates.update_fail_htlcs.is_empty());
4935                 assert!(updates.update_fail_malformed_htlcs.is_empty());
4936                 assert!(updates.update_fee.is_none());
4937                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4938                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
4939                 check_added_monitors!(nodes[1], 1);
4940                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4941                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
4942
4943                 assert!(updates_2.update_add_htlcs.is_empty());
4944                 assert!(updates_2.update_fail_htlcs.is_empty());
4945                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
4946                 assert!(updates_2.update_fee.is_none());
4947                 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
4948                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
4949                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
4950
4951                 let events = nodes[0].node.get_and_clear_pending_events();
4952                 assert_eq!(events.len(), 1);
4953                 match events[0] {
4954                         Event::PaymentSent { ref payment_preimage } => {
4955                                 assert_eq!(our_payment_preimage, *payment_preimage);
4956                         },
4957                         _ => panic!("Unexpected event"),
4958                 }
4959
4960                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4961                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4962                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4963                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4964                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4965                 assert!(node_0_none.is_none());
4966
4967                 assert!(nodes[0].node.list_channels().is_empty());
4968
4969                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4970                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
4971                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
4972                 assert!(nodes[1].node.list_channels().is_empty());
4973                 assert!(nodes[2].node.list_channels().is_empty());
4974         }
4975
4976         #[test]
4977         fn htlc_fail_async_shutdown() {
4978                 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
4979                 let mut nodes = create_network(3);
4980                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4981                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4982
4983                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4984                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4985                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
4986                 check_added_monitors!(nodes[0], 1);
4987                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4988                 assert_eq!(updates.update_add_htlcs.len(), 1);
4989                 assert!(updates.update_fulfill_htlcs.is_empty());
4990                 assert!(updates.update_fail_htlcs.is_empty());
4991                 assert!(updates.update_fail_malformed_htlcs.is_empty());
4992                 assert!(updates.update_fee.is_none());
4993
4994                 nodes[1].node.close_channel(&chan_1.2).unwrap();
4995                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4996                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4997                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4998
4999                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5000                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
5001                 check_added_monitors!(nodes[1], 1);
5002                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
5003                 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
5004
5005                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5006                 assert!(updates_2.update_add_htlcs.is_empty());
5007                 assert!(updates_2.update_fulfill_htlcs.is_empty());
5008                 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
5009                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
5010                 assert!(updates_2.update_fee.is_none());
5011
5012                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]).unwrap();
5013                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
5014
5015                 let events = nodes[0].node.get_and_clear_pending_events();
5016                 assert_eq!(events.len(), 1);
5017                 match events[0] {
5018                         Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } => {
5019                                 assert_eq!(our_payment_hash, *payment_hash);
5020                                 assert!(!rejected_by_dest);
5021                         },
5022                         _ => panic!("Unexpected event"),
5023                 }
5024
5025                 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5026                 assert_eq!(msg_events.len(), 2);
5027                 let node_0_closing_signed = match msg_events[0] {
5028                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
5029                                 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5030                                 (*msg).clone()
5031                         },
5032                         _ => panic!("Unexpected event"),
5033                 };
5034                 match msg_events[1] {
5035                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
5036                                 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
5037                         },
5038                         _ => panic!("Unexpected event"),
5039                 }
5040
5041                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5042                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5043                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5044                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5045                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5046                 assert!(node_0_none.is_none());
5047
5048                 assert!(nodes[0].node.list_channels().is_empty());
5049
5050                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5051                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5052                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5053                 assert!(nodes[1].node.list_channels().is_empty());
5054                 assert!(nodes[2].node.list_channels().is_empty());
5055         }
5056
5057         fn do_test_shutdown_rebroadcast(recv_count: u8) {
5058                 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
5059                 // messages delivered prior to disconnect
5060                 let nodes = create_network(3);
5061                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5062                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5063
5064                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
5065
5066                 nodes[1].node.close_channel(&chan_1.2).unwrap();
5067                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5068                 if recv_count > 0 {
5069                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
5070                         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5071                         if recv_count > 1 {
5072                                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
5073                         }
5074                 }
5075
5076                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5077                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5078
5079                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5080                 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5081                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5082                 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5083
5084                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish).unwrap();
5085                 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5086                 assert!(node_1_shutdown == node_1_2nd_shutdown);
5087
5088                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish).unwrap();
5089                 let node_0_2nd_shutdown = if recv_count > 0 {
5090                         let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5091                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5092                         node_0_2nd_shutdown
5093                 } else {
5094                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5095                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5096                         get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
5097                 };
5098                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown).unwrap();
5099
5100                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5101                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5102
5103                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
5104                 check_added_monitors!(nodes[2], 1);
5105                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5106                 assert!(updates.update_add_htlcs.is_empty());
5107                 assert!(updates.update_fail_htlcs.is_empty());
5108                 assert!(updates.update_fail_malformed_htlcs.is_empty());
5109                 assert!(updates.update_fee.is_none());
5110                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5111                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
5112                 check_added_monitors!(nodes[1], 1);
5113                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5114                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
5115
5116                 assert!(updates_2.update_add_htlcs.is_empty());
5117                 assert!(updates_2.update_fail_htlcs.is_empty());
5118                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
5119                 assert!(updates_2.update_fee.is_none());
5120                 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
5121                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
5122                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
5123
5124                 let events = nodes[0].node.get_and_clear_pending_events();
5125                 assert_eq!(events.len(), 1);
5126                 match events[0] {
5127                         Event::PaymentSent { ref payment_preimage } => {
5128                                 assert_eq!(our_payment_preimage, *payment_preimage);
5129                         },
5130                         _ => panic!("Unexpected event"),
5131                 }
5132
5133                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5134                 if recv_count > 0 {
5135                         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5136                         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5137                         assert!(node_1_closing_signed.is_some());
5138                 }
5139
5140                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5141                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5142
5143                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5144                 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5145                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5146                 if recv_count == 0 {
5147                         // If all closing_signeds weren't delivered we can just resume where we left off...
5148                         let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5149
5150                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish).unwrap();
5151                         let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5152                         assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
5153
5154                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish).unwrap();
5155                         let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5156                         assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
5157
5158                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown).unwrap();
5159                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5160
5161                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown).unwrap();
5162                         let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5163                         assert!(node_0_closing_signed == node_0_2nd_closing_signed);
5164
5165                         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed).unwrap();
5166                         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5167                         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5168                         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5169                         assert!(node_0_none.is_none());
5170                 } else {
5171                         // If one node, however, received + responded with an identical closing_signed we end
5172                         // up erroring and node[0] will try to broadcast its own latest commitment transaction.
5173                         // There isn't really anything better we can do simply, but in the future we might
5174                         // explore storing a set of recently-closed channels that got disconnected during
5175                         // closing_signed and avoiding broadcasting local commitment txn for some timeout to
5176                         // give our counterparty enough time to (potentially) broadcast a cooperative closing
5177                         // transaction.
5178                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5179
5180                         if let Err(msgs::HandleError{action: Some(msgs::ErrorAction::SendErrorMessage{msg}), ..}) =
5181                                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish) {
5182                                 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
5183                                 let msgs::ErrorMessage {ref channel_id, ..} = msg;
5184                                 assert_eq!(*channel_id, chan_1.2);
5185                         } else { panic!("Needed SendErrorMessage close"); }
5186
5187                         // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
5188                         // checks it, but in this case nodes[0] didn't ever get a chance to receive a
5189                         // closing_signed so we do it ourselves
5190                         let events = nodes[0].node.get_and_clear_pending_msg_events();
5191                         assert_eq!(events.len(), 1);
5192                         match events[0] {
5193                                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5194                                         assert_eq!(msg.contents.flags & 2, 2);
5195                                 },
5196                                 _ => panic!("Unexpected event"),
5197                         }
5198                 }
5199
5200                 assert!(nodes[0].node.list_channels().is_empty());
5201
5202                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5203                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5204                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5205                 assert!(nodes[1].node.list_channels().is_empty());
5206                 assert!(nodes[2].node.list_channels().is_empty());
5207         }
5208
5209         #[test]
5210         fn test_shutdown_rebroadcast() {
5211                 do_test_shutdown_rebroadcast(0);
5212                 do_test_shutdown_rebroadcast(1);
5213                 do_test_shutdown_rebroadcast(2);
5214         }
5215
5216         #[test]
5217         fn fake_network_test() {
5218                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5219                 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
5220                 let nodes = create_network(4);
5221
5222                 // Create some initial channels
5223                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5224                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5225                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5226
5227                 // Rebalance the network a bit by relaying one payment through all the channels...
5228                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5229                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5230                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5231                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5232
5233                 // Send some more payments
5234                 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
5235                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
5236                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
5237
5238                 // Test failure packets
5239                 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
5240                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
5241
5242                 // Add a new channel that skips 3
5243                 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
5244
5245                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
5246                 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
5247                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5248                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5249                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5250                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5251                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5252
5253                 // Do some rebalance loop payments, simultaneously
5254                 let mut hops = Vec::with_capacity(3);
5255                 hops.push(RouteHop {
5256                         pubkey: nodes[2].node.get_our_node_id(),
5257                         short_channel_id: chan_2.0.contents.short_channel_id,
5258                         fee_msat: 0,
5259                         cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
5260                 });
5261                 hops.push(RouteHop {
5262                         pubkey: nodes[3].node.get_our_node_id(),
5263                         short_channel_id: chan_3.0.contents.short_channel_id,
5264                         fee_msat: 0,
5265                         cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
5266                 });
5267                 hops.push(RouteHop {
5268                         pubkey: nodes[1].node.get_our_node_id(),
5269                         short_channel_id: chan_4.0.contents.short_channel_id,
5270                         fee_msat: 1000000,
5271                         cltv_expiry_delta: TEST_FINAL_CLTV,
5272                 });
5273                 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;
5274                 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;
5275                 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
5276
5277                 let mut hops = Vec::with_capacity(3);
5278                 hops.push(RouteHop {
5279                         pubkey: nodes[3].node.get_our_node_id(),
5280                         short_channel_id: chan_4.0.contents.short_channel_id,
5281                         fee_msat: 0,
5282                         cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
5283                 });
5284                 hops.push(RouteHop {
5285                         pubkey: nodes[2].node.get_our_node_id(),
5286                         short_channel_id: chan_3.0.contents.short_channel_id,
5287                         fee_msat: 0,
5288                         cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
5289                 });
5290                 hops.push(RouteHop {
5291                         pubkey: nodes[1].node.get_our_node_id(),
5292                         short_channel_id: chan_2.0.contents.short_channel_id,
5293                         fee_msat: 1000000,
5294                         cltv_expiry_delta: TEST_FINAL_CLTV,
5295                 });
5296                 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;
5297                 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;
5298                 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
5299
5300                 // Claim the rebalances...
5301                 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
5302                 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
5303
5304                 // Add a duplicate new channel from 2 to 4
5305                 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3);
5306
5307                 // Send some payments across both channels
5308                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5309                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5310                 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5311
5312                 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
5313
5314                 //TODO: Test that routes work again here as we've been notified that the channel is full
5315
5316                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
5317                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
5318                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
5319
5320                 // Close down the channels...
5321                 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
5322                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
5323                 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
5324                 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
5325                 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
5326         }
5327
5328         #[test]
5329         fn duplicate_htlc_test() {
5330                 // Test that we accept duplicate payment_hash HTLCs across the network and that
5331                 // claiming/failing them are all separate and don't effect each other
5332                 let mut nodes = create_network(6);
5333
5334                 // Create some initial channels to route via 3 to 4/5 from 0/1/2
5335                 create_announced_chan_between_nodes(&nodes, 0, 3);
5336                 create_announced_chan_between_nodes(&nodes, 1, 3);
5337                 create_announced_chan_between_nodes(&nodes, 2, 3);
5338                 create_announced_chan_between_nodes(&nodes, 3, 4);
5339                 create_announced_chan_between_nodes(&nodes, 3, 5);
5340
5341                 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
5342
5343                 *nodes[0].network_payment_count.borrow_mut() -= 1;
5344                 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
5345
5346                 *nodes[0].network_payment_count.borrow_mut() -= 1;
5347                 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
5348
5349                 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
5350                 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
5351                 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
5352         }
5353
5354         #[derive(PartialEq)]
5355         enum HTLCType { NONE, TIMEOUT, SUCCESS }
5356         /// Tests that the given node has broadcast transactions for the given Channel
5357         ///
5358         /// First checks that the latest local commitment tx has been broadcast, unless an explicit
5359         /// commitment_tx is provided, which may be used to test that a remote commitment tx was
5360         /// broadcast and the revoked outputs were claimed.
5361         ///
5362         /// Next tests that there is (or is not) a transaction that spends the commitment transaction
5363         /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
5364         ///
5365         /// All broadcast transactions must be accounted for in one of the above three types of we'll
5366         /// also fail.
5367         fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
5368                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5369                 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
5370
5371                 let mut res = Vec::with_capacity(2);
5372                 node_txn.retain(|tx| {
5373                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
5374                                 check_spends!(tx, chan.3.clone());
5375                                 if commitment_tx.is_none() {
5376                                         res.push(tx.clone());
5377                                 }
5378                                 false
5379                         } else { true }
5380                 });
5381                 if let Some(explicit_tx) = commitment_tx {
5382                         res.push(explicit_tx.clone());
5383                 }
5384
5385                 assert_eq!(res.len(), 1);
5386
5387                 if has_htlc_tx != HTLCType::NONE {
5388                         node_txn.retain(|tx| {
5389                                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
5390                                         check_spends!(tx, res[0].clone());
5391                                         if has_htlc_tx == HTLCType::TIMEOUT {
5392                                                 assert!(tx.lock_time != 0);
5393                                         } else {
5394                                                 assert!(tx.lock_time == 0);
5395                                         }
5396                                         res.push(tx.clone());
5397                                         false
5398                                 } else { true }
5399                         });
5400                         assert!(res.len() == 2 || res.len() == 3);
5401                         if res.len() == 3 {
5402                                 assert_eq!(res[1], res[2]);
5403                         }
5404                 }
5405
5406                 assert!(node_txn.is_empty());
5407                 res
5408         }
5409
5410         /// Tests that the given node has broadcast a claim transaction against the provided revoked
5411         /// HTLC transaction.
5412         fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
5413                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5414                 assert_eq!(node_txn.len(), 1);
5415                 node_txn.retain(|tx| {
5416                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
5417                                 check_spends!(tx, revoked_tx.clone());
5418                                 false
5419                         } else { true }
5420                 });
5421                 assert!(node_txn.is_empty());
5422         }
5423
5424         fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
5425                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5426
5427                 assert!(node_txn.len() >= 1);
5428                 assert_eq!(node_txn[0].input.len(), 1);
5429                 let mut found_prev = false;
5430
5431                 for tx in prev_txn {
5432                         if node_txn[0].input[0].previous_output.txid == tx.txid() {
5433                                 check_spends!(node_txn[0], tx.clone());
5434                                 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
5435                                 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
5436
5437                                 found_prev = true;
5438                                 break;
5439                         }
5440                 }
5441                 assert!(found_prev);
5442
5443                 let mut res = Vec::new();
5444                 mem::swap(&mut *node_txn, &mut res);
5445                 res
5446         }
5447
5448         fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
5449                 let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
5450                 assert_eq!(events_1.len(), 1);
5451                 let as_update = match events_1[0] {
5452                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5453                                 msg.clone()
5454                         },
5455                         _ => panic!("Unexpected event"),
5456                 };
5457
5458                 let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
5459                 assert_eq!(events_2.len(), 1);
5460                 let bs_update = match events_2[0] {
5461                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5462                                 msg.clone()
5463                         },
5464                         _ => panic!("Unexpected event"),
5465                 };
5466
5467                 for node in nodes {
5468                         node.router.handle_channel_update(&as_update).unwrap();
5469                         node.router.handle_channel_update(&bs_update).unwrap();
5470                 }
5471         }
5472
5473         macro_rules! expect_pending_htlcs_forwardable {
5474                 ($node: expr) => {{
5475                         let events = $node.node.get_and_clear_pending_events();
5476                         assert_eq!(events.len(), 1);
5477                         match events[0] {
5478                                 Event::PendingHTLCsForwardable { .. } => { },
5479                                 _ => panic!("Unexpected event"),
5480                         };
5481                         $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
5482                         $node.node.process_pending_htlc_forwards();
5483                 }}
5484         }
5485
5486         fn do_channel_reserve_test(test_recv: bool) {
5487                 use util::rng;
5488                 use std::sync::atomic::Ordering;
5489                 use ln::msgs::HandleError;
5490
5491                 macro_rules! get_channel_value_stat {
5492                         ($node: expr, $channel_id: expr) => {{
5493                                 let chan_lock = $node.node.channel_state.lock().unwrap();
5494                                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
5495                                 chan.get_value_stat()
5496                         }}
5497                 }
5498
5499                 let mut nodes = create_network(3);
5500                 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001);
5501                 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001);
5502
5503                 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
5504                 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
5505
5506                 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
5507                 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
5508
5509                 macro_rules! get_route_and_payment_hash {
5510                         ($recv_value: expr) => {{
5511                                 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
5512                                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5513                                 (route, payment_hash, payment_preimage)
5514                         }}
5515                 };
5516
5517                 macro_rules! expect_forward {
5518                         ($node: expr) => {{
5519                                 let mut events = $node.node.get_and_clear_pending_msg_events();
5520                                 assert_eq!(events.len(), 1);
5521                                 check_added_monitors!($node, 1);
5522                                 let payment_event = SendEvent::from_event(events.remove(0));
5523                                 payment_event
5524                         }}
5525                 }
5526
5527                 macro_rules! expect_payment_received {
5528                         ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
5529                                 let events = $node.node.get_and_clear_pending_events();
5530                                 assert_eq!(events.len(), 1);
5531                                 match events[0] {
5532                                         Event::PaymentReceived { ref payment_hash, amt } => {
5533                                                 assert_eq!($expected_payment_hash, *payment_hash);
5534                                                 assert_eq!($expected_recv_value, amt);
5535                                         },
5536                                         _ => panic!("Unexpected event"),
5537                                 }
5538                         }
5539                 };
5540
5541                 let feemsat = 239; // somehow we know?
5542                 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
5543
5544                 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
5545
5546                 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
5547                 {
5548                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
5549                         assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
5550                         let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
5551                         match err {
5552                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
5553                                 _ => panic!("Unknown error variants"),
5554                         }
5555                 }
5556
5557                 let mut htlc_id = 0;
5558                 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
5559                 // nodes[0]'s wealth
5560                 loop {
5561                         let amt_msat = recv_value_0 + total_fee_msat;
5562                         if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
5563                                 break;
5564                         }
5565                         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
5566                         htlc_id += 1;
5567
5568                         let (stat01_, stat11_, stat12_, stat22_) = (
5569                                 get_channel_value_stat!(nodes[0], chan_1.2),
5570                                 get_channel_value_stat!(nodes[1], chan_1.2),
5571                                 get_channel_value_stat!(nodes[1], chan_2.2),
5572                                 get_channel_value_stat!(nodes[2], chan_2.2),
5573                         );
5574
5575                         assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
5576                         assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
5577                         assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
5578                         assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
5579                         stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
5580                 }
5581
5582                 {
5583                         let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
5584                         // attempt to get channel_reserve violation
5585                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
5586                         let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
5587                         match err {
5588                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5589                                 _ => panic!("Unknown error variants"),
5590                         }
5591                 }
5592
5593                 // adding pending output
5594                 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
5595                 let amt_msat_1 = recv_value_1 + total_fee_msat;
5596
5597                 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
5598                 let payment_event_1 = {
5599                         nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
5600                         check_added_monitors!(nodes[0], 1);
5601
5602                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5603                         assert_eq!(events.len(), 1);
5604                         SendEvent::from_event(events.remove(0))
5605                 };
5606                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]).unwrap();
5607
5608                 // channel reserve test with htlc pending output > 0
5609                 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
5610                 {
5611                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5612                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5613                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5614                                 _ => panic!("Unknown error variants"),
5615                         }
5616                 }
5617
5618                 {
5619                         // test channel_reserve test on nodes[1] side
5620                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5621
5622                         // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
5623                         let secp_ctx = Secp256k1::new();
5624                         let session_priv = SecretKey::from_slice(&secp_ctx, &{
5625                                 let mut session_key = [0; 32];
5626                                 rng::fill_bytes(&mut session_key);
5627                                 session_key
5628                         }).expect("RNG is bad!");
5629
5630                         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5631                         let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
5632                         let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height).unwrap();
5633                         let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
5634                         let msg = msgs::UpdateAddHTLC {
5635                                 channel_id: chan_1.2,
5636                                 htlc_id,
5637                                 amount_msat: htlc_msat,
5638                                 payment_hash: our_payment_hash,
5639                                 cltv_expiry: htlc_cltv,
5640                                 onion_routing_packet: onion_packet,
5641                         };
5642
5643                         if test_recv {
5644                                 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).err().unwrap();
5645                                 match err {
5646                                         HandleError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
5647                                 }
5648                                 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
5649                                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5650                                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5651                                 let channel_close_broadcast = nodes[1].node.get_and_clear_pending_msg_events();
5652                                 assert_eq!(channel_close_broadcast.len(), 1);
5653                                 match channel_close_broadcast[0] {
5654                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5655                                                 assert_eq!(msg.contents.flags & 2, 2);
5656                                         },
5657                                         _ => panic!("Unexpected event"),
5658                                 }
5659                                 return;
5660                         }
5661                 }
5662
5663                 // split the rest to test holding cell
5664                 let recv_value_21 = recv_value_2/2;
5665                 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
5666                 {
5667                         let stat = get_channel_value_stat!(nodes[0], chan_1.2);
5668                         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);
5669                 }
5670
5671                 // now see if they go through on both sides
5672                 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
5673                 // but this will stuck in the holding cell
5674                 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
5675                 check_added_monitors!(nodes[0], 0);
5676                 let events = nodes[0].node.get_and_clear_pending_events();
5677                 assert_eq!(events.len(), 0);
5678
5679                 // test with outbound holding cell amount > 0
5680                 {
5681                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
5682                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5683                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5684                                 _ => panic!("Unknown error variants"),
5685                         }
5686                 }
5687
5688                 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
5689                 // this will also stuck in the holding cell
5690                 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
5691                 check_added_monitors!(nodes[0], 0);
5692                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
5693                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5694
5695                 // flush the pending htlc
5696                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg).unwrap();
5697                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5698                 check_added_monitors!(nodes[1], 1);
5699
5700                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
5701                 check_added_monitors!(nodes[0], 1);
5702                 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5703
5704                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed).unwrap();
5705                 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
5706                 // No commitment_signed so get_event_msg's assert(len == 1) passes
5707                 check_added_monitors!(nodes[0], 1);
5708
5709                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
5710                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5711                 check_added_monitors!(nodes[1], 1);
5712
5713                 expect_pending_htlcs_forwardable!(nodes[1]);
5714
5715                 let ref payment_event_11 = expect_forward!(nodes[1]);
5716                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]).unwrap();
5717                 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
5718
5719                 expect_pending_htlcs_forwardable!(nodes[2]);
5720                 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
5721
5722                 // flush the htlcs in the holding cell
5723                 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
5724                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]).unwrap();
5725                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]).unwrap();
5726                 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
5727                 expect_pending_htlcs_forwardable!(nodes[1]);
5728
5729                 let ref payment_event_3 = expect_forward!(nodes[1]);
5730                 assert_eq!(payment_event_3.msgs.len(), 2);
5731                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]).unwrap();
5732                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]).unwrap();
5733
5734                 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
5735                 expect_pending_htlcs_forwardable!(nodes[2]);
5736
5737                 let events = nodes[2].node.get_and_clear_pending_events();
5738                 assert_eq!(events.len(), 2);
5739                 match events[0] {
5740                         Event::PaymentReceived { ref payment_hash, amt } => {
5741                                 assert_eq!(our_payment_hash_21, *payment_hash);
5742                                 assert_eq!(recv_value_21, amt);
5743                         },
5744                         _ => panic!("Unexpected event"),
5745                 }
5746                 match events[1] {
5747                         Event::PaymentReceived { ref payment_hash, amt } => {
5748                                 assert_eq!(our_payment_hash_22, *payment_hash);
5749                                 assert_eq!(recv_value_22, amt);
5750                         },
5751                         _ => panic!("Unexpected event"),
5752                 }
5753
5754                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
5755                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
5756                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
5757
5758                 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);
5759                 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
5760                 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
5761                 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
5762
5763                 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
5764                 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
5765         }
5766
5767         #[test]
5768         fn channel_reserve_test() {
5769                 do_channel_reserve_test(false);
5770                 do_channel_reserve_test(true);
5771         }
5772
5773         #[test]
5774         fn channel_monitor_network_test() {
5775                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5776                 // tests that ChannelMonitor is able to recover from various states.
5777                 let nodes = create_network(5);
5778
5779                 // Create some initial channels
5780                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5781                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5782                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5783                 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5784
5785                 // Rebalance the network a bit by relaying one payment through all the channels...
5786                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5787                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5788                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5789                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5790
5791                 // Simple case with no pending HTLCs:
5792                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
5793                 {
5794                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
5795                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5796                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5797                         test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
5798                 }
5799                 get_announce_close_broadcast_events(&nodes, 0, 1);
5800                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5801                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5802
5803                 // One pending HTLC is discarded by the force-close:
5804                 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
5805
5806                 // Simple case of one pending HTLC to HTLC-Timeout
5807                 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
5808                 {
5809                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
5810                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5811                         nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5812                         test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
5813                 }
5814                 get_announce_close_broadcast_events(&nodes, 1, 2);
5815                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5816                 assert_eq!(nodes[2].node.list_channels().len(), 1);
5817
5818                 macro_rules! claim_funds {
5819                         ($node: expr, $prev_node: expr, $preimage: expr) => {
5820                                 {
5821                                         assert!($node.node.claim_funds($preimage));
5822                                         check_added_monitors!($node, 1);
5823
5824                                         let events = $node.node.get_and_clear_pending_msg_events();
5825                                         assert_eq!(events.len(), 1);
5826                                         match events[0] {
5827                                                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
5828                                                         assert!(update_add_htlcs.is_empty());
5829                                                         assert!(update_fail_htlcs.is_empty());
5830                                                         assert_eq!(*node_id, $prev_node.node.get_our_node_id());
5831                                                 },
5832                                                 _ => panic!("Unexpected event"),
5833                                         };
5834                                 }
5835                         }
5836                 }
5837
5838                 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
5839                 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
5840                 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
5841                 {
5842                         let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
5843
5844                         // Claim the payment on nodes[3], giving it knowledge of the preimage
5845                         claim_funds!(nodes[3], nodes[2], payment_preimage_1);
5846
5847                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5848                         nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
5849
5850                         check_preimage_claim(&nodes[3], &node_txn);
5851                 }
5852                 get_announce_close_broadcast_events(&nodes, 2, 3);
5853                 assert_eq!(nodes[2].node.list_channels().len(), 0);
5854                 assert_eq!(nodes[3].node.list_channels().len(), 1);
5855
5856                 { // Cheat and reset nodes[4]'s height to 1
5857                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5858                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![] }, 1);
5859                 }
5860
5861                 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
5862                 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
5863                 // One pending HTLC to time out:
5864                 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
5865                 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
5866                 // buffer space).
5867
5868                 {
5869                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5870                         nodes[3].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5871                         for i in 3..TEST_FINAL_CLTV + 2 + HTLC_FAIL_TIMEOUT_BLOCKS + 1 {
5872                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5873                                 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5874                         }
5875
5876                         let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
5877
5878                         // Claim the payment on nodes[4], giving it knowledge of the preimage
5879                         claim_funds!(nodes[4], nodes[3], payment_preimage_2);
5880
5881                         header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5882                         nodes[4].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5883                         for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
5884                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5885                                 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5886                         }
5887
5888                         test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
5889
5890                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5891                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
5892
5893                         check_preimage_claim(&nodes[4], &node_txn);
5894                 }
5895                 get_announce_close_broadcast_events(&nodes, 3, 4);
5896                 assert_eq!(nodes[3].node.list_channels().len(), 0);
5897                 assert_eq!(nodes[4].node.list_channels().len(), 0);
5898         }
5899
5900         #[test]
5901         fn test_justice_tx() {
5902                 // Test justice txn built on revoked HTLC-Success tx, against both sides
5903
5904                 let nodes = create_network(2);
5905                 // Create some new channels:
5906                 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
5907
5908                 // A pending HTLC which will be revoked:
5909                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5910                 // Get the will-be-revoked local txn from nodes[0]
5911                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5912                 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
5913                 assert_eq!(revoked_local_txn[0].input.len(), 1);
5914                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
5915                 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
5916                 assert_eq!(revoked_local_txn[1].input.len(), 1);
5917                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
5918                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
5919                 // Revoke the old state
5920                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
5921
5922                 {
5923                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5924                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5925                         {
5926                                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5927                                 assert_eq!(node_txn.len(), 3);
5928                                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5929                                 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
5930
5931                                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5932                                 node_txn.swap_remove(0);
5933                         }
5934                         test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
5935
5936                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5937                         let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
5938                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5939                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5940                         test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
5941                 }
5942                 get_announce_close_broadcast_events(&nodes, 0, 1);
5943
5944                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5945                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5946
5947                 // We test justice_tx build by A on B's revoked HTLC-Success tx
5948                 // Create some new channels:
5949                 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
5950
5951                 // A pending HTLC which will be revoked:
5952                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5953                 // Get the will-be-revoked local txn from B
5954                 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5955                 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
5956                 assert_eq!(revoked_local_txn[0].input.len(), 1);
5957                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
5958                 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
5959                 // Revoke the old state
5960                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
5961                 {
5962                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5963                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5964                         {
5965                                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5966                                 assert_eq!(node_txn.len(), 3);
5967                                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5968                                 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
5969
5970                                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5971                                 node_txn.swap_remove(0);
5972                         }
5973                         test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
5974
5975                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5976                         let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
5977                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5978                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5979                         test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone());
5980                 }
5981                 get_announce_close_broadcast_events(&nodes, 0, 1);
5982                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5983                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5984         }
5985
5986         #[test]
5987         fn revoked_output_claim() {
5988                 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
5989                 // transaction is broadcast by its counterparty
5990                 let nodes = create_network(2);
5991                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5992                 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
5993                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5994                 assert_eq!(revoked_local_txn.len(), 1);
5995                 // Only output is the full channel value back to nodes[0]:
5996                 assert_eq!(revoked_local_txn[0].output.len(), 1);
5997                 // Send a payment through, updating everyone's latest commitment txn
5998                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
5999
6000                 // Inform nodes[1] that nodes[0] broadcast a stale tx
6001                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6002                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6003                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6004                 assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
6005
6006                 assert_eq!(node_txn[0], node_txn[2]);
6007
6008                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
6009                 check_spends!(node_txn[1], chan_1.3.clone());
6010
6011                 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
6012                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6013                 get_announce_close_broadcast_events(&nodes, 0, 1);
6014         }
6015
6016         #[test]
6017         fn claim_htlc_outputs_shared_tx() {
6018                 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
6019                 let nodes = create_network(2);
6020
6021                 // Create some new channel:
6022                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6023
6024                 // Rebalance the network to generate htlc in the two directions
6025                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6026                 // 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
6027                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6028                 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6029
6030                 // Get the will-be-revoked local txn from node[0]
6031                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6032                 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
6033                 assert_eq!(revoked_local_txn[0].input.len(), 1);
6034                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
6035                 assert_eq!(revoked_local_txn[1].input.len(), 1);
6036                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
6037                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
6038                 check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
6039
6040                 //Revoke the old state
6041                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6042
6043                 {
6044                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6045                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6046                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6047
6048                         let events = nodes[1].node.get_and_clear_pending_events();
6049                         assert_eq!(events.len(), 1);
6050                         match events[0] {
6051                                 Event::PaymentFailed { payment_hash, .. } => {
6052                                         assert_eq!(payment_hash, payment_hash_2);
6053                                 },
6054                                 _ => panic!("Unexpected event"),
6055                         }
6056
6057                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6058                         assert_eq!(node_txn.len(), 4);
6059
6060                         assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
6061                         check_spends!(node_txn[0], revoked_local_txn[0].clone());
6062
6063                         assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
6064
6065                         let mut witness_lens = BTreeSet::new();
6066                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6067                         witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
6068                         witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
6069                         assert_eq!(witness_lens.len(), 3);
6070                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6071                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
6072                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
6073
6074                         // Next nodes[1] broadcasts its current local tx state:
6075                         assert_eq!(node_txn[1].input.len(), 1);
6076                         assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
6077
6078                         assert_eq!(node_txn[2].input.len(), 1);
6079                         let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
6080                         assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
6081                         assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
6082                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6083                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
6084                 }
6085                 get_announce_close_broadcast_events(&nodes, 0, 1);
6086                 assert_eq!(nodes[0].node.list_channels().len(), 0);
6087                 assert_eq!(nodes[1].node.list_channels().len(), 0);
6088         }
6089
6090         #[test]
6091         fn claim_htlc_outputs_single_tx() {
6092                 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
6093                 let nodes = create_network(2);
6094
6095                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6096
6097                 // Rebalance the network to generate htlc in the two directions
6098                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6099                 // 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
6100                 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
6101                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6102                 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6103
6104                 // Get the will-be-revoked local txn from node[0]
6105                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6106
6107                 //Revoke the old state
6108                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6109
6110                 {
6111                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6112                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6113                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6114
6115                         let events = nodes[1].node.get_and_clear_pending_events();
6116                         assert_eq!(events.len(), 1);
6117                         match events[0] {
6118                                 Event::PaymentFailed { payment_hash, .. } => {
6119                                         assert_eq!(payment_hash, payment_hash_2);
6120                                 },
6121                                 _ => panic!("Unexpected event"),
6122                         }
6123
6124                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6125                         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)
6126
6127                         assert_eq!(node_txn[0], node_txn[7]);
6128                         assert_eq!(node_txn[1], node_txn[8]);
6129                         assert_eq!(node_txn[2], node_txn[9]);
6130                         assert_eq!(node_txn[3], node_txn[10]);
6131                         assert_eq!(node_txn[4], node_txn[11]);
6132                         assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcated by ChannelManger
6133                         assert_eq!(node_txn[4], node_txn[6]);
6134
6135                         assert_eq!(node_txn[0].input.len(), 1);
6136                         assert_eq!(node_txn[1].input.len(), 1);
6137                         assert_eq!(node_txn[2].input.len(), 1);
6138
6139                         let mut revoked_tx_map = HashMap::new();
6140                         revoked_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
6141                         node_txn[0].verify(&revoked_tx_map).unwrap();
6142                         node_txn[1].verify(&revoked_tx_map).unwrap();
6143                         node_txn[2].verify(&revoked_tx_map).unwrap();
6144
6145                         let mut witness_lens = BTreeSet::new();
6146                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6147                         witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
6148                         witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
6149                         assert_eq!(witness_lens.len(), 3);
6150                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6151                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
6152                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
6153
6154                         assert_eq!(node_txn[3].input.len(), 1);
6155                         check_spends!(node_txn[3], chan_1.3.clone());
6156
6157                         assert_eq!(node_txn[4].input.len(), 1);
6158                         let witness_script = node_txn[4].input[0].witness.last().unwrap();
6159                         assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
6160                         assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
6161                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6162                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
6163                 }
6164                 get_announce_close_broadcast_events(&nodes, 0, 1);
6165                 assert_eq!(nodes[0].node.list_channels().len(), 0);
6166                 assert_eq!(nodes[1].node.list_channels().len(), 0);
6167         }
6168
6169         #[test]
6170         fn test_htlc_on_chain_success() {
6171                 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
6172                 // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
6173                 // broadcasting the right event to other nodes in payment path.
6174                 // A --------------------> B ----------------------> C (preimage)
6175                 // First, C should claim the HTLC output via HTLC-Success when its own latest local
6176                 // commitment transaction was broadcast.
6177                 // Then, B should learn the preimage from said transactions, attempting to claim backwards
6178                 // towards B.
6179                 // B should be able to claim via preimage if A then broadcasts its local tx.
6180                 // Finally, when A sees B's latest local commitment transaction it should be able to claim
6181                 // the HTLC output via the preimage it learned (which, once confirmed should generate a
6182                 // PaymentSent event).
6183
6184                 let nodes = create_network(3);
6185
6186                 // Create some initial channels
6187                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6188                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6189
6190                 // Rebalance the network a bit by relaying one payment through all the channels...
6191                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6192                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6193
6194                 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
6195                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6196
6197                 // Broadcast legit commitment tx from C on B's chain
6198                 // Broadcast HTLC Success transation by C on received output from C's commitment tx on B's chain
6199                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6200                 assert_eq!(commitment_tx.len(), 1);
6201                 check_spends!(commitment_tx[0], chan_2.3.clone());
6202                 nodes[2].node.claim_funds(our_payment_preimage);
6203                 check_added_monitors!(nodes[2], 1);
6204                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6205                 assert!(updates.update_add_htlcs.is_empty());
6206                 assert!(updates.update_fail_htlcs.is_empty());
6207                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6208                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
6209
6210                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6211                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6212                 assert_eq!(events.len(), 1);
6213                 match events[0] {
6214                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6215                         _ => panic!("Unexpected event"),
6216                 }
6217                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
6218                 assert_eq!(node_txn.len(), 3);
6219                 assert_eq!(node_txn[1], commitment_tx[0]);
6220                 assert_eq!(node_txn[0], node_txn[2]);
6221                 check_spends!(node_txn[0], commitment_tx[0].clone());
6222                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6223                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6224                 assert_eq!(node_txn[0].lock_time, 0);
6225
6226                 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
6227                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: node_txn}, 1);
6228                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6229                 {
6230                         let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
6231                         assert_eq!(added_monitors.len(), 1);
6232                         assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
6233                         added_monitors.clear();
6234                 }
6235                 assert_eq!(events.len(), 2);
6236                 match events[0] {
6237                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6238                         _ => panic!("Unexpected event"),
6239                 }
6240                 match events[1] {
6241                         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, .. } } => {
6242                                 assert!(update_add_htlcs.is_empty());
6243                                 assert!(update_fail_htlcs.is_empty());
6244                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6245                                 assert!(update_fail_malformed_htlcs.is_empty());
6246                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6247                         },
6248                         _ => panic!("Unexpected event"),
6249                 };
6250                 {
6251                         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
6252                         // commitment transaction with a corresponding HTLC-Timeout transaction, as well as a
6253                         // timeout-claim of the output that nodes[2] just claimed via success.
6254                         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)
6255                         assert_eq!(node_txn.len(), 4);
6256                         assert_eq!(node_txn[0], node_txn[3]);
6257                         check_spends!(node_txn[0], commitment_tx[0].clone());
6258                         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6259                         assert_ne!(node_txn[0].lock_time, 0);
6260                         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
6261                         check_spends!(node_txn[1], chan_2.3.clone());
6262                         check_spends!(node_txn[2], node_txn[1].clone());
6263                         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6264                         assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6265                         assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6266                         assert_ne!(node_txn[2].lock_time, 0);
6267                         node_txn.clear();
6268                 }
6269
6270                 // Broadcast legit commitment tx from A on B's chain
6271                 // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
6272                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6273                 check_spends!(commitment_tx[0], chan_1.3.clone());
6274                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6275                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6276                 assert_eq!(events.len(), 1);
6277                 match events[0] {
6278                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6279                         _ => panic!("Unexpected event"),
6280                 }
6281                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 1 (HTLC-Success) * 2 (block-rescan)
6282                 assert_eq!(node_txn.len(), 3);
6283                 assert_eq!(node_txn[0], node_txn[2]);
6284                 check_spends!(node_txn[0], commitment_tx[0].clone());
6285                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6286                 assert_eq!(node_txn[0].lock_time, 0);
6287                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
6288                 check_spends!(node_txn[1], chan_1.3.clone());
6289                 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6290                 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
6291                 // we already checked the same situation with A.
6292
6293                 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
6294                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
6295                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6296                 assert_eq!(events.len(), 1);
6297                 match events[0] {
6298                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6299                         _ => panic!("Unexpected event"),
6300                 }
6301                 let events = nodes[0].node.get_and_clear_pending_events();
6302                 assert_eq!(events.len(), 1);
6303                 match events[0] {
6304                         Event::PaymentSent { payment_preimage } => {
6305                                 assert_eq!(payment_preimage, our_payment_preimage);
6306                         },
6307                         _ => panic!("Unexpected event"),
6308                 }
6309                 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)
6310                 assert_eq!(node_txn.len(), 4);
6311                 assert_eq!(node_txn[0], node_txn[3]);
6312                 check_spends!(node_txn[0], commitment_tx[0].clone());
6313                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6314                 assert_ne!(node_txn[0].lock_time, 0);
6315                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6316                 check_spends!(node_txn[1], chan_1.3.clone());
6317                 check_spends!(node_txn[2], node_txn[1].clone());
6318                 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6319                 assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6320                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6321                 assert_ne!(node_txn[2].lock_time, 0);
6322         }
6323
6324         #[test]
6325         fn test_htlc_on_chain_timeout() {
6326                 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
6327                 // ChainWatchInterface and timeout the HTLC  bacward accordingly. So here we test that ChannelManager is
6328                 // broadcasting the right event to other nodes in payment path.
6329                 // A ------------------> B ----------------------> C (timeout)
6330                 //    B's commitment tx                 C's commitment tx
6331                 //            \                                  \
6332                 //         B's HTLC timeout tx               B's timeout tx
6333
6334                 let nodes = create_network(3);
6335
6336                 // Create some intial channels
6337                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6338                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6339
6340                 // Rebalance the network a bit by relaying one payment thorugh all the channels...
6341                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6342                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6343
6344                 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
6345                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6346
6347                 // Brodacast legit commitment tx from C on B's chain
6348                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6349                 check_spends!(commitment_tx[0], chan_2.3.clone());
6350                 nodes[2].node.fail_htlc_backwards(&payment_hash, PaymentFailReason::PreimageUnknown);
6351                 {
6352                         let mut added_monitors = nodes[2].chan_monitor.added_monitors.lock().unwrap();
6353                         assert_eq!(added_monitors.len(), 1);
6354                         added_monitors.clear();
6355                 }
6356                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6357                 assert_eq!(events.len(), 1);
6358                 match events[0] {
6359                         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, .. } } => {
6360                                 assert!(update_add_htlcs.is_empty());
6361                                 assert!(!update_fail_htlcs.is_empty());
6362                                 assert!(update_fulfill_htlcs.is_empty());
6363                                 assert!(update_fail_malformed_htlcs.is_empty());
6364                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
6365                         },
6366                         _ => panic!("Unexpected event"),
6367                 };
6368                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6369                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6370                 assert_eq!(events.len(), 1);
6371                 match events[0] {
6372                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6373                         _ => panic!("Unexpected event"),
6374                 }
6375                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
6376                 assert_eq!(node_txn.len(), 1);
6377                 check_spends!(node_txn[0], chan_2.3.clone());
6378                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
6379
6380                 // Broadcast timeout transaction by B on received output fron C's commitment tx on B's chain
6381                 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
6382                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6383                 let timeout_tx;
6384                 {
6385                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6386                         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)
6387                         assert_eq!(node_txn[0], node_txn[5]);
6388                         assert_eq!(node_txn[1], node_txn[6]);
6389                         assert_eq!(node_txn[2], node_txn[7]);
6390                         check_spends!(node_txn[0], commitment_tx[0].clone());
6391                         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6392                         check_spends!(node_txn[1], chan_2.3.clone());
6393                         check_spends!(node_txn[2], node_txn[1].clone());
6394                         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6395                         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6396                         check_spends!(node_txn[3], chan_2.3.clone());
6397                         check_spends!(node_txn[4], node_txn[3].clone());
6398                         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
6399                         assert_eq!(node_txn[4].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6400                         timeout_tx = node_txn[0].clone();
6401                         node_txn.clear();
6402                 }
6403
6404                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![timeout_tx]}, 1);
6405                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6406                 check_added_monitors!(nodes[1], 1);
6407                 assert_eq!(events.len(), 2);
6408                 match events[0] {
6409                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6410                         _ => panic!("Unexpected event"),
6411                 }
6412                 match events[1] {
6413                         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, .. } } => {
6414                                 assert!(update_add_htlcs.is_empty());
6415                                 assert!(!update_fail_htlcs.is_empty());
6416                                 assert!(update_fulfill_htlcs.is_empty());
6417                                 assert!(update_fail_malformed_htlcs.is_empty());
6418                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6419                         },
6420                         _ => panic!("Unexpected event"),
6421                 };
6422                 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
6423                 assert_eq!(node_txn.len(), 0);
6424
6425                 // Broadcast legit commitment tx from B on A's chain
6426                 let commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6427                 check_spends!(commitment_tx[0], chan_1.3.clone());
6428
6429                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6430                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6431                 assert_eq!(events.len(), 1);
6432                 match events[0] {
6433                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6434                         _ => panic!("Unexpected event"),
6435                 }
6436                 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
6437                 assert_eq!(node_txn.len(), 4);
6438                 assert_eq!(node_txn[0], node_txn[3]);
6439                 check_spends!(node_txn[0], commitment_tx[0].clone());
6440                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6441                 check_spends!(node_txn[1], chan_1.3.clone());
6442                 check_spends!(node_txn[2], node_txn[1].clone());
6443                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6444                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6445         }
6446
6447         #[test]
6448         fn test_simple_commitment_revoked_fail_backward() {
6449                 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
6450                 // and fail backward accordingly.
6451
6452                 let nodes = create_network(3);
6453
6454                 // Create some initial channels
6455                 create_announced_chan_between_nodes(&nodes, 0, 1);
6456                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6457
6458                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6459                 // Get the will-be-revoked local txn from nodes[2]
6460                 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6461                 // Revoke the old state
6462                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6463
6464                 route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6465
6466                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6467                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6468                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6469                 check_added_monitors!(nodes[1], 1);
6470                 assert_eq!(events.len(), 2);
6471                 match events[0] {
6472                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6473                         _ => panic!("Unexpected event"),
6474                 }
6475                 match events[1] {
6476                         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, .. } } => {
6477                                 assert!(update_add_htlcs.is_empty());
6478                                 assert_eq!(update_fail_htlcs.len(), 1);
6479                                 assert!(update_fulfill_htlcs.is_empty());
6480                                 assert!(update_fail_malformed_htlcs.is_empty());
6481                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6482
6483                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6484                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6485
6486                                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6487                                 assert_eq!(events.len(), 1);
6488                                 match events[0] {
6489                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6490                                         _ => panic!("Unexpected event"),
6491                                 }
6492                                 let events = nodes[0].node.get_and_clear_pending_events();
6493                                 assert_eq!(events.len(), 1);
6494                                 match events[0] {
6495                                         Event::PaymentFailed { .. } => {},
6496                                         _ => panic!("Unexpected event"),
6497                                 }
6498                         },
6499                         _ => panic!("Unexpected event"),
6500                 }
6501         }
6502
6503         fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool) {
6504                 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
6505                 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
6506                 // commitment transaction anymore.
6507                 // To do this, we have the peer which will broadcast a revoked commitment transaction send
6508                 // a number of update_fail/commitment_signed updates without ever sending the RAA in
6509                 // response to our commitment_signed. This is somewhat misbehavior-y, though not
6510                 // technically disallowed and we should probably handle it reasonably.
6511                 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
6512                 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
6513                 // transactions:
6514                 // * Once we move it out of our holding cell/add it, we will immediately include it in a
6515                 //   commitment_signed (implying it will be in the latest remote commitment transaction).
6516                 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
6517                 //   and once they revoke the previous commitment transaction (allowing us to send a new
6518                 //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
6519                 let mut nodes = create_network(3);
6520
6521                 // Create some initial channels
6522                 create_announced_chan_between_nodes(&nodes, 0, 1);
6523                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6524
6525                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6526                 // Get the will-be-revoked local txn from nodes[2]
6527                 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6528                 // Revoke the old state
6529                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6530
6531                 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6532                 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6533                 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6534
6535                 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, PaymentFailReason::PreimageUnknown));
6536                 check_added_monitors!(nodes[2], 1);
6537                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6538                 assert!(updates.update_add_htlcs.is_empty());
6539                 assert!(updates.update_fulfill_htlcs.is_empty());
6540                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6541                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6542                 assert!(updates.update_fee.is_none());
6543                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6544                 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
6545                 // Drop the last RAA from 3 -> 2
6546
6547                 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, PaymentFailReason::PreimageUnknown));
6548                 check_added_monitors!(nodes[2], 1);
6549                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6550                 assert!(updates.update_add_htlcs.is_empty());
6551                 assert!(updates.update_fulfill_htlcs.is_empty());
6552                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6553                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6554                 assert!(updates.update_fee.is_none());
6555                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6556                 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6557                 check_added_monitors!(nodes[1], 1);
6558                 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
6559                 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6560                 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6561                 check_added_monitors!(nodes[2], 1);
6562
6563                 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, PaymentFailReason::PreimageUnknown));
6564                 check_added_monitors!(nodes[2], 1);
6565                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6566                 assert!(updates.update_add_htlcs.is_empty());
6567                 assert!(updates.update_fulfill_htlcs.is_empty());
6568                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6569                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6570                 assert!(updates.update_fee.is_none());
6571                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6572                 // At this point first_payment_hash has dropped out of the latest two commitment
6573                 // transactions that nodes[1] is tracking...
6574                 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6575                 check_added_monitors!(nodes[1], 1);
6576                 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
6577                 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6578                 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6579                 check_added_monitors!(nodes[2], 1);
6580
6581                 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
6582                 // on nodes[2]'s RAA.
6583                 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
6584                 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6585                 nodes[1].node.send_payment(route, fourth_payment_hash).unwrap();
6586                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
6587                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6588                 check_added_monitors!(nodes[1], 0);
6589
6590                 if deliver_bs_raa {
6591                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa).unwrap();
6592                         // One monitor for the new revocation preimage, one as we generate a commitment for
6593                         // nodes[0] to fail first_payment_hash backwards.
6594                         check_added_monitors!(nodes[1], 2);
6595                 }
6596
6597                 let mut failed_htlcs = HashSet::new();
6598                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6599
6600                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6601                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6602
6603                 let events = nodes[1].node.get_and_clear_pending_events();
6604                 assert_eq!(events.len(), 1);
6605                 match events[0] {
6606                         Event::PaymentFailed { ref payment_hash, .. } => {
6607                                 assert_eq!(*payment_hash, fourth_payment_hash);
6608                         },
6609                         _ => panic!("Unexpected event"),
6610                 }
6611
6612                 if !deliver_bs_raa {
6613                         // If we delivered the RAA already then we already failed first_payment_hash backwards.
6614                         check_added_monitors!(nodes[1], 1);
6615                 }
6616
6617                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6618                 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
6619                 match events[if deliver_bs_raa { 2 } else { 0 }] {
6620                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6621                         _ => panic!("Unexpected event"),
6622                 }
6623                 if deliver_bs_raa {
6624                         match events[0] {
6625                                 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, .. } } => {
6626                                         assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
6627                                         assert_eq!(update_add_htlcs.len(), 1);
6628                                         assert!(update_fulfill_htlcs.is_empty());
6629                                         assert!(update_fail_htlcs.is_empty());
6630                                         assert!(update_fail_malformed_htlcs.is_empty());
6631                                 },
6632                                 _ => panic!("Unexpected event"),
6633                         }
6634                 }
6635                 // Due to the way backwards-failing occurs we do the updates in two steps.
6636                 let updates = match events[1] {
6637                         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, .. } } => {
6638                                 assert!(update_add_htlcs.is_empty());
6639                                 assert_eq!(update_fail_htlcs.len(), 1);
6640                                 assert!(update_fulfill_htlcs.is_empty());
6641                                 assert!(update_fail_malformed_htlcs.is_empty());
6642                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6643
6644                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6645                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
6646                                 check_added_monitors!(nodes[0], 1);
6647                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6648                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6649                                 check_added_monitors!(nodes[1], 1);
6650                                 let bs_second_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6651                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
6652                                 check_added_monitors!(nodes[1], 1);
6653                                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6654                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6655                                 check_added_monitors!(nodes[0], 1);
6656
6657                                 if !deliver_bs_raa {
6658                                         // If we delievered B's RAA we got an unknown preimage error, not something
6659                                         // that we should update our routing table for.
6660                                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6661                                         assert_eq!(events.len(), 1);
6662                                         match events[0] {
6663                                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6664                                                 _ => panic!("Unexpected event"),
6665                                         }
6666                                 }
6667                                 let events = nodes[0].node.get_and_clear_pending_events();
6668                                 assert_eq!(events.len(), 1);
6669                                 match events[0] {
6670                                         Event::PaymentFailed { ref payment_hash, .. } => {
6671                                                 assert!(failed_htlcs.insert(payment_hash.0));
6672                                         },
6673                                         _ => panic!("Unexpected event"),
6674                                 }
6675
6676                                 bs_second_update
6677                         },
6678                         _ => panic!("Unexpected event"),
6679                 };
6680
6681                 assert!(updates.update_add_htlcs.is_empty());
6682                 assert_eq!(updates.update_fail_htlcs.len(), 2);
6683                 assert!(updates.update_fulfill_htlcs.is_empty());
6684                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6685                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6686                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[1]).unwrap();
6687                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6688
6689                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6690                 assert_eq!(events.len(), 2);
6691                 for event in events {
6692                         match event {
6693                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6694                                 _ => panic!("Unexpected event"),
6695                         }
6696                 }
6697
6698                 let events = nodes[0].node.get_and_clear_pending_events();
6699                 assert_eq!(events.len(), 2);
6700                 match events[0] {
6701                         Event::PaymentFailed { ref payment_hash, .. } => {
6702                                 assert!(failed_htlcs.insert(payment_hash.0));
6703                         },
6704                         _ => panic!("Unexpected event"),
6705                 }
6706                 match events[1] {
6707                         Event::PaymentFailed { ref payment_hash, .. } => {
6708                                 assert!(failed_htlcs.insert(payment_hash.0));
6709                         },
6710                         _ => panic!("Unexpected event"),
6711                 }
6712
6713                 assert!(failed_htlcs.contains(&first_payment_hash.0));
6714                 assert!(failed_htlcs.contains(&second_payment_hash.0));
6715                 assert!(failed_htlcs.contains(&third_payment_hash.0));
6716         }
6717
6718         #[test]
6719         fn test_commitment_revoked_fail_backward_exhaustive() {
6720                 do_test_commitment_revoked_fail_backward_exhaustive(false);
6721                 do_test_commitment_revoked_fail_backward_exhaustive(true);
6722         }
6723
6724         #[test]
6725         fn test_htlc_ignore_latest_remote_commitment() {
6726                 // Test that HTLC transactions spending the latest remote commitment transaction are simply
6727                 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
6728                 let nodes = create_network(2);
6729                 create_announced_chan_between_nodes(&nodes, 0, 1);
6730
6731                 route_payment(&nodes[0], &[&nodes[1]], 10000000);
6732                 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
6733                 {
6734                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6735                         assert_eq!(events.len(), 1);
6736                         match events[0] {
6737                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6738                                         assert_eq!(flags & 0b10, 0b10);
6739                                 },
6740                                 _ => panic!("Unexpected event"),
6741                         }
6742                 }
6743
6744                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6745                 assert_eq!(node_txn.len(), 2);
6746
6747                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6748                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6749
6750                 {
6751                         let events = nodes[1].node.get_and_clear_pending_msg_events();
6752                         assert_eq!(events.len(), 1);
6753                         match events[0] {
6754                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6755                                         assert_eq!(flags & 0b10, 0b10);
6756                                 },
6757                                 _ => panic!("Unexpected event"),
6758                         }
6759                 }
6760
6761                 // Duplicate the block_connected call since this may happen due to other listeners
6762                 // registering new transactions
6763                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6764         }
6765
6766         #[test]
6767         fn test_force_close_fail_back() {
6768                 // Check which HTLCs are failed-backwards on channel force-closure
6769                 let mut nodes = create_network(3);
6770                 create_announced_chan_between_nodes(&nodes, 0, 1);
6771                 create_announced_chan_between_nodes(&nodes, 1, 2);
6772
6773                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
6774
6775                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6776
6777                 let mut payment_event = {
6778                         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6779                         check_added_monitors!(nodes[0], 1);
6780
6781                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6782                         assert_eq!(events.len(), 1);
6783                         SendEvent::from_event(events.remove(0))
6784                 };
6785
6786                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6787                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6788
6789                 let events_1 = nodes[1].node.get_and_clear_pending_events();
6790                 assert_eq!(events_1.len(), 1);
6791                 match events_1[0] {
6792                         Event::PendingHTLCsForwardable { .. } => { },
6793                         _ => panic!("Unexpected event"),
6794                 };
6795
6796                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
6797                 nodes[1].node.process_pending_htlc_forwards();
6798
6799                 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6800                 assert_eq!(events_2.len(), 1);
6801                 payment_event = SendEvent::from_event(events_2.remove(0));
6802                 assert_eq!(payment_event.msgs.len(), 1);
6803
6804                 check_added_monitors!(nodes[1], 1);
6805                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6806                 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
6807                 check_added_monitors!(nodes[2], 1);
6808                 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6809
6810                 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
6811                 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
6812                 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
6813
6814                 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
6815                 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6816                 assert_eq!(events_3.len(), 1);
6817                 match events_3[0] {
6818                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6819                                 assert_eq!(flags & 0b10, 0b10);
6820                         },
6821                         _ => panic!("Unexpected event"),
6822                 }
6823
6824                 let tx = {
6825                         let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6826                         // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
6827                         // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
6828                         // back to nodes[1] upon timeout otherwise.
6829                         assert_eq!(node_txn.len(), 1);
6830                         node_txn.remove(0)
6831                 };
6832
6833                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6834                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6835
6836                 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6837                 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
6838                 assert_eq!(events_4.len(), 1);
6839                 match events_4[0] {
6840                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6841                                 assert_eq!(flags & 0b10, 0b10);
6842                         },
6843                         _ => panic!("Unexpected event"),
6844                 }
6845
6846                 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
6847                 {
6848                         let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
6849                         monitors.get_mut(&OutPoint::new(Sha256dHash::from(&payment_event.commitment_msg.channel_id[..]), 0)).unwrap()
6850                                 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
6851                 }
6852                 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6853                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6854                 assert_eq!(node_txn.len(), 1);
6855                 assert_eq!(node_txn[0].input.len(), 1);
6856                 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
6857                 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
6858                 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
6859
6860                 check_spends!(node_txn[0], tx);
6861         }
6862
6863         #[test]
6864         fn test_unconf_chan() {
6865                 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
6866                 let nodes = create_network(2);
6867                 create_announced_chan_between_nodes(&nodes, 0, 1);
6868
6869                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6870                 assert_eq!(channel_state.by_id.len(), 1);
6871                 assert_eq!(channel_state.short_to_id.len(), 1);
6872                 mem::drop(channel_state);
6873
6874                 let mut headers = Vec::new();
6875                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6876                 headers.push(header.clone());
6877                 for _i in 2..100 {
6878                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6879                         headers.push(header.clone());
6880                 }
6881                 while !headers.is_empty() {
6882                         nodes[0].node.block_disconnected(&headers.pop().unwrap());
6883                 }
6884                 {
6885                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6886                         assert_eq!(events.len(), 1);
6887                         match events[0] {
6888                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6889                                         assert_eq!(flags & 0b10, 0b10);
6890                                 },
6891                                 _ => panic!("Unexpected event"),
6892                         }
6893                 }
6894                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6895                 assert_eq!(channel_state.by_id.len(), 0);
6896                 assert_eq!(channel_state.short_to_id.len(), 0);
6897         }
6898
6899         macro_rules! get_chan_reestablish_msgs {
6900                 ($src_node: expr, $dst_node: expr) => {
6901                         {
6902                                 let mut res = Vec::with_capacity(1);
6903                                 for msg in $src_node.node.get_and_clear_pending_msg_events() {
6904                                         if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
6905                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6906                                                 res.push(msg.clone());
6907                                         } else {
6908                                                 panic!("Unexpected event")
6909                                         }
6910                                 }
6911                                 res
6912                         }
6913                 }
6914         }
6915
6916         macro_rules! handle_chan_reestablish_msgs {
6917                 ($src_node: expr, $dst_node: expr) => {
6918                         {
6919                                 let msg_events = $src_node.node.get_and_clear_pending_msg_events();
6920                                 let mut idx = 0;
6921                                 let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
6922                                         idx += 1;
6923                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6924                                         Some(msg.clone())
6925                                 } else {
6926                                         None
6927                                 };
6928
6929                                 let mut revoke_and_ack = None;
6930                                 let mut commitment_update = None;
6931                                 let order = if let Some(ev) = msg_events.get(idx) {
6932                                         idx += 1;
6933                                         match ev {
6934                                                 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6935                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6936                                                         revoke_and_ack = Some(msg.clone());
6937                                                         RAACommitmentOrder::RevokeAndACKFirst
6938                                                 },
6939                                                 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6940                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6941                                                         commitment_update = Some(updates.clone());
6942                                                         RAACommitmentOrder::CommitmentFirst
6943                                                 },
6944                                                 _ => panic!("Unexpected event"),
6945                                         }
6946                                 } else {
6947                                         RAACommitmentOrder::CommitmentFirst
6948                                 };
6949
6950                                 if let Some(ev) = msg_events.get(idx) {
6951                                         match ev {
6952                                                 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6953                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6954                                                         assert!(revoke_and_ack.is_none());
6955                                                         revoke_and_ack = Some(msg.clone());
6956                                                 },
6957                                                 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6958                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6959                                                         assert!(commitment_update.is_none());
6960                                                         commitment_update = Some(updates.clone());
6961                                                 },
6962                                                 _ => panic!("Unexpected event"),
6963                                         }
6964                                 }
6965
6966                                 (funding_locked, revoke_and_ack, commitment_update, order)
6967                         }
6968                 }
6969         }
6970
6971         /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
6972         /// for claims/fails they are separated out.
6973         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)) {
6974                 node_a.node.peer_connected(&node_b.node.get_our_node_id());
6975                 let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
6976                 node_b.node.peer_connected(&node_a.node.get_our_node_id());
6977                 let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
6978
6979                 if send_funding_locked.0 {
6980                         // If a expects a funding_locked, it better not think it has received a revoke_and_ack
6981                         // from b
6982                         for reestablish in reestablish_1.iter() {
6983                                 assert_eq!(reestablish.next_remote_commitment_number, 0);
6984                         }
6985                 }
6986                 if send_funding_locked.1 {
6987                         // If b expects a funding_locked, it better not think it has received a revoke_and_ack
6988                         // from a
6989                         for reestablish in reestablish_2.iter() {
6990                                 assert_eq!(reestablish.next_remote_commitment_number, 0);
6991                         }
6992                 }
6993                 if send_funding_locked.0 || send_funding_locked.1 {
6994                         // If we expect any funding_locked's, both sides better have set
6995                         // next_local_commitment_number to 1
6996                         for reestablish in reestablish_1.iter() {
6997                                 assert_eq!(reestablish.next_local_commitment_number, 1);
6998                         }
6999                         for reestablish in reestablish_2.iter() {
7000                                 assert_eq!(reestablish.next_local_commitment_number, 1);
7001                         }
7002                 }
7003
7004                 let mut resp_1 = Vec::new();
7005                 for msg in reestablish_1 {
7006                         node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg).unwrap();
7007                         resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
7008                 }
7009                 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
7010                         check_added_monitors!(node_b, 1);
7011                 } else {
7012                         check_added_monitors!(node_b, 0);
7013                 }
7014
7015                 let mut resp_2 = Vec::new();
7016                 for msg in reestablish_2 {
7017                         node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg).unwrap();
7018                         resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
7019                 }
7020                 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
7021                         check_added_monitors!(node_a, 1);
7022                 } else {
7023                         check_added_monitors!(node_a, 0);
7024                 }
7025
7026                 // We dont yet support both needing updates, as that would require a different commitment dance:
7027                 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
7028                         (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
7029
7030                 for chan_msgs in resp_1.drain(..) {
7031                         if send_funding_locked.0 {
7032                                 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
7033                                 let announcement_event = node_a.node.get_and_clear_pending_msg_events();
7034                                 if !announcement_event.is_empty() {
7035                                         assert_eq!(announcement_event.len(), 1);
7036                                         if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
7037                                                 //TODO: Test announcement_sigs re-sending
7038                                         } else { panic!("Unexpected event!"); }
7039                                 }
7040                         } else {
7041                                 assert!(chan_msgs.0.is_none());
7042                         }
7043                         if pending_raa.0 {
7044                                 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
7045                                 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
7046                                 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
7047                                 check_added_monitors!(node_a, 1);
7048                         } else {
7049                                 assert!(chan_msgs.1.is_none());
7050                         }
7051                         if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
7052                                 let commitment_update = chan_msgs.2.unwrap();
7053                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
7054                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
7055                                 } else {
7056                                         assert!(commitment_update.update_add_htlcs.is_empty());
7057                                 }
7058                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
7059                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
7060                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
7061                                 for update_add in commitment_update.update_add_htlcs {
7062                                         node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add).unwrap();
7063                                 }
7064                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
7065                                         node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill).unwrap();
7066                                 }
7067                                 for update_fail in commitment_update.update_fail_htlcs {
7068                                         node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail).unwrap();
7069                                 }
7070
7071                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
7072                                         commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
7073                                 } else {
7074                                         node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
7075                                         check_added_monitors!(node_a, 1);
7076                                         let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
7077                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
7078                                         node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7079                                         assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
7080                                         check_added_monitors!(node_b, 1);
7081                                 }
7082                         } else {
7083                                 assert!(chan_msgs.2.is_none());
7084                         }
7085                 }
7086
7087                 for chan_msgs in resp_2.drain(..) {
7088                         if send_funding_locked.1 {
7089                                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
7090                                 let announcement_event = node_b.node.get_and_clear_pending_msg_events();
7091                                 if !announcement_event.is_empty() {
7092                                         assert_eq!(announcement_event.len(), 1);
7093                                         if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
7094                                                 //TODO: Test announcement_sigs re-sending
7095                                         } else { panic!("Unexpected event!"); }
7096                                 }
7097                         } else {
7098                                 assert!(chan_msgs.0.is_none());
7099                         }
7100                         if pending_raa.1 {
7101                                 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
7102                                 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
7103                                 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
7104                                 check_added_monitors!(node_b, 1);
7105                         } else {
7106                                 assert!(chan_msgs.1.is_none());
7107                         }
7108                         if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
7109                                 let commitment_update = chan_msgs.2.unwrap();
7110                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
7111                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
7112                                 }
7113                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
7114                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
7115                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
7116                                 for update_add in commitment_update.update_add_htlcs {
7117                                         node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add).unwrap();
7118                                 }
7119                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
7120                                         node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill).unwrap();
7121                                 }
7122                                 for update_fail in commitment_update.update_fail_htlcs {
7123                                         node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail).unwrap();
7124                                 }
7125
7126                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
7127                                         commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
7128                                 } else {
7129                                         node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
7130                                         check_added_monitors!(node_b, 1);
7131                                         let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
7132                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
7133                                         node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7134                                         assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
7135                                         check_added_monitors!(node_a, 1);
7136                                 }
7137                         } else {
7138                                 assert!(chan_msgs.2.is_none());
7139                         }
7140                 }
7141         }
7142
7143         #[test]
7144         fn test_simple_peer_disconnect() {
7145                 // Test that we can reconnect when there are no lost messages
7146                 let nodes = create_network(3);
7147                 create_announced_chan_between_nodes(&nodes, 0, 1);
7148                 create_announced_chan_between_nodes(&nodes, 1, 2);
7149
7150                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7151                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7152                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7153
7154                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7155                 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7156                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
7157                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
7158
7159                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7160                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7161                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7162
7163                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7164                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7165                 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7166                 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7167
7168                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7169                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7170
7171                 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3);
7172                 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
7173
7174                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
7175                 {
7176                         let events = nodes[0].node.get_and_clear_pending_events();
7177                         assert_eq!(events.len(), 2);
7178                         match events[0] {
7179                                 Event::PaymentSent { payment_preimage } => {
7180                                         assert_eq!(payment_preimage, payment_preimage_3);
7181                                 },
7182                                 _ => panic!("Unexpected event"),
7183                         }
7184                         match events[1] {
7185                                 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
7186                                         assert_eq!(payment_hash, payment_hash_5);
7187                                         assert!(rejected_by_dest);
7188                                 },
7189                                 _ => panic!("Unexpected event"),
7190                         }
7191                 }
7192
7193                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
7194                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
7195         }
7196
7197         fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
7198                 // Test that we can reconnect when in-flight HTLC updates get dropped
7199                 let mut nodes = create_network(2);
7200                 if messages_delivered == 0 {
7201                         create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
7202                         // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
7203                 } else {
7204                         create_announced_chan_between_nodes(&nodes, 0, 1);
7205                 }
7206
7207                 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();
7208                 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7209
7210                 let payment_event = {
7211                         nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
7212                         check_added_monitors!(nodes[0], 1);
7213
7214                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7215                         assert_eq!(events.len(), 1);
7216                         SendEvent::from_event(events.remove(0))
7217                 };
7218                 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
7219
7220                 if messages_delivered < 2 {
7221                         // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
7222                 } else {
7223                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7224                         if messages_delivered >= 3 {
7225                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7226                                 check_added_monitors!(nodes[1], 1);
7227                                 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7228
7229                                 if messages_delivered >= 4 {
7230                                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7231                                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7232                                         check_added_monitors!(nodes[0], 1);
7233
7234                                         if messages_delivered >= 5 {
7235                                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
7236                                                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7237                                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7238                                                 check_added_monitors!(nodes[0], 1);
7239
7240                                                 if messages_delivered >= 6 {
7241                                                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7242                                                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7243                                                         check_added_monitors!(nodes[1], 1);
7244                                                 }
7245                                         }
7246                                 }
7247                         }
7248                 }
7249
7250                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7251                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7252                 if messages_delivered < 3 {
7253                         // Even if the funding_locked messages get exchanged, as long as nothing further was
7254                         // received on either side, both sides will need to resend them.
7255                         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
7256                 } else if messages_delivered == 3 {
7257                         // nodes[0] still wants its RAA + commitment_signed
7258                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
7259                 } else if messages_delivered == 4 {
7260                         // nodes[0] still wants its commitment_signed
7261                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
7262                 } else if messages_delivered == 5 {
7263                         // nodes[1] still wants its final RAA
7264                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
7265                 } else if messages_delivered == 6 {
7266                         // Everything was delivered...
7267                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7268                 }
7269
7270                 let events_1 = nodes[1].node.get_and_clear_pending_events();
7271                 assert_eq!(events_1.len(), 1);
7272                 match events_1[0] {
7273                         Event::PendingHTLCsForwardable { .. } => { },
7274                         _ => panic!("Unexpected event"),
7275                 };
7276
7277                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7278                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7279                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7280
7281                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7282                 nodes[1].node.process_pending_htlc_forwards();
7283
7284                 let events_2 = nodes[1].node.get_and_clear_pending_events();
7285                 assert_eq!(events_2.len(), 1);
7286                 match events_2[0] {
7287                         Event::PaymentReceived { ref payment_hash, amt } => {
7288                                 assert_eq!(payment_hash_1, *payment_hash);
7289                                 assert_eq!(amt, 1000000);
7290                         },
7291                         _ => panic!("Unexpected event"),
7292                 }
7293
7294                 nodes[1].node.claim_funds(payment_preimage_1);
7295                 check_added_monitors!(nodes[1], 1);
7296
7297                 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
7298                 assert_eq!(events_3.len(), 1);
7299                 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
7300                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
7301                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7302                                 assert!(updates.update_add_htlcs.is_empty());
7303                                 assert!(updates.update_fail_htlcs.is_empty());
7304                                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
7305                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
7306                                 assert!(updates.update_fee.is_none());
7307                                 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
7308                         },
7309                         _ => panic!("Unexpected event"),
7310                 };
7311
7312                 if messages_delivered >= 1 {
7313                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc).unwrap();
7314
7315                         let events_4 = nodes[0].node.get_and_clear_pending_events();
7316                         assert_eq!(events_4.len(), 1);
7317                         match events_4[0] {
7318                                 Event::PaymentSent { ref payment_preimage } => {
7319                                         assert_eq!(payment_preimage_1, *payment_preimage);
7320                                 },
7321                                 _ => panic!("Unexpected event"),
7322                         }
7323
7324                         if messages_delivered >= 2 {
7325                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
7326                                 check_added_monitors!(nodes[0], 1);
7327                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7328
7329                                 if messages_delivered >= 3 {
7330                                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7331                                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7332                                         check_added_monitors!(nodes[1], 1);
7333
7334                                         if messages_delivered >= 4 {
7335                                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
7336                                                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7337                                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7338                                                 check_added_monitors!(nodes[1], 1);
7339
7340                                                 if messages_delivered >= 5 {
7341                                                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7342                                                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7343                                                         check_added_monitors!(nodes[0], 1);
7344                                                 }
7345                                         }
7346                                 }
7347                         }
7348                 }
7349
7350                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7351                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7352                 if messages_delivered < 2 {
7353                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
7354                         //TODO: Deduplicate PaymentSent events, then enable this if:
7355                         //if messages_delivered < 1 {
7356                                 let events_4 = nodes[0].node.get_and_clear_pending_events();
7357                                 assert_eq!(events_4.len(), 1);
7358                                 match events_4[0] {
7359                                         Event::PaymentSent { ref payment_preimage } => {
7360                                                 assert_eq!(payment_preimage_1, *payment_preimage);
7361                                         },
7362                                         _ => panic!("Unexpected event"),
7363                                 }
7364                         //}
7365                 } else if messages_delivered == 2 {
7366                         // nodes[0] still wants its RAA + commitment_signed
7367                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
7368                 } else if messages_delivered == 3 {
7369                         // nodes[0] still wants its commitment_signed
7370                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
7371                 } else if messages_delivered == 4 {
7372                         // nodes[1] still wants its final RAA
7373                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
7374                 } else if messages_delivered == 5 {
7375                         // Everything was delivered...
7376                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7377                 }
7378
7379                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7380                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7381                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7382
7383                 // Channel should still work fine...
7384                 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
7385                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7386         }
7387
7388         #[test]
7389         fn test_drop_messages_peer_disconnect_a() {
7390                 do_test_drop_messages_peer_disconnect(0);
7391                 do_test_drop_messages_peer_disconnect(1);
7392                 do_test_drop_messages_peer_disconnect(2);
7393                 do_test_drop_messages_peer_disconnect(3);
7394         }
7395
7396         #[test]
7397         fn test_drop_messages_peer_disconnect_b() {
7398                 do_test_drop_messages_peer_disconnect(4);
7399                 do_test_drop_messages_peer_disconnect(5);
7400                 do_test_drop_messages_peer_disconnect(6);
7401         }
7402
7403         #[test]
7404         fn test_funding_peer_disconnect() {
7405                 // Test that we can lock in our funding tx while disconnected
7406                 let nodes = create_network(2);
7407                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
7408
7409                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7410                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7411
7412                 confirm_transaction(&nodes[0].chain_monitor, &tx, tx.version);
7413                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7414                 assert_eq!(events_1.len(), 1);
7415                 match events_1[0] {
7416                         MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7417                                 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7418                         },
7419                         _ => panic!("Unexpected event"),
7420                 }
7421
7422                 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7423
7424                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7425                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7426
7427                 confirm_transaction(&nodes[1].chain_monitor, &tx, tx.version);
7428                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7429                 assert_eq!(events_2.len(), 2);
7430                 match events_2[0] {
7431                         MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7432                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7433                         },
7434                         _ => panic!("Unexpected event"),
7435                 }
7436                 match events_2[1] {
7437                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ } => {
7438                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7439                         },
7440                         _ => panic!("Unexpected event"),
7441                 }
7442
7443                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7444
7445                 // TODO: We shouldn't need to manually pass list_usable_chanels here once we support
7446                 // rebroadcasting announcement_signatures upon reconnect.
7447
7448                 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();
7449                 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
7450                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
7451         }
7452
7453         #[test]
7454         fn test_drop_messages_peer_disconnect_dual_htlc() {
7455                 // Test that we can handle reconnecting when both sides of a channel have pending
7456                 // commitment_updates when we disconnect.
7457                 let mut nodes = create_network(2);
7458                 create_announced_chan_between_nodes(&nodes, 0, 1);
7459
7460                 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7461
7462                 // Now try to send a second payment which will fail to send
7463                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7464                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7465
7466                 nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
7467                 check_added_monitors!(nodes[0], 1);
7468
7469                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7470                 assert_eq!(events_1.len(), 1);
7471                 match events_1[0] {
7472                         MessageSendEvent::UpdateHTLCs { .. } => {},
7473                         _ => panic!("Unexpected event"),
7474                 }
7475
7476                 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7477                 check_added_monitors!(nodes[1], 1);
7478
7479                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7480                 assert_eq!(events_2.len(), 1);
7481                 match events_2[0] {
7482                         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 } } => {
7483                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7484                                 assert!(update_add_htlcs.is_empty());
7485                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7486                                 assert!(update_fail_htlcs.is_empty());
7487                                 assert!(update_fail_malformed_htlcs.is_empty());
7488                                 assert!(update_fee.is_none());
7489
7490                                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7491                                 let events_3 = nodes[0].node.get_and_clear_pending_events();
7492                                 assert_eq!(events_3.len(), 1);
7493                                 match events_3[0] {
7494                                         Event::PaymentSent { ref payment_preimage } => {
7495                                                 assert_eq!(*payment_preimage, payment_preimage_1);
7496                                         },
7497                                         _ => panic!("Unexpected event"),
7498                                 }
7499
7500                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
7501                                 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7502                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7503                                 check_added_monitors!(nodes[0], 1);
7504                         },
7505                         _ => panic!("Unexpected event"),
7506                 }
7507
7508                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7509                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7510
7511                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7512                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7513                 assert_eq!(reestablish_1.len(), 1);
7514                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7515                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7516                 assert_eq!(reestablish_2.len(), 1);
7517
7518                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7519                 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7520                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7521                 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7522
7523                 assert!(as_resp.0.is_none());
7524                 assert!(bs_resp.0.is_none());
7525
7526                 assert!(bs_resp.1.is_none());
7527                 assert!(bs_resp.2.is_none());
7528
7529                 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7530
7531                 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
7532                 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
7533                 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7534                 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7535                 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
7536                 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();
7537                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7538                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7539                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7540                 check_added_monitors!(nodes[1], 1);
7541
7542                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap();
7543                 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7544                 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
7545                 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
7546                 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
7547                 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
7548                 assert!(bs_second_commitment_signed.update_fee.is_none());
7549                 check_added_monitors!(nodes[1], 1);
7550
7551                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7552                 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7553                 assert!(as_commitment_signed.update_add_htlcs.is_empty());
7554                 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
7555                 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
7556                 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
7557                 assert!(as_commitment_signed.update_fee.is_none());
7558                 check_added_monitors!(nodes[0], 1);
7559
7560                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
7561                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7562                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7563                 check_added_monitors!(nodes[0], 1);
7564
7565                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
7566                 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7567                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7568                 check_added_monitors!(nodes[1], 1);
7569
7570                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7571                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7572                 check_added_monitors!(nodes[1], 1);
7573
7574                 let events_4 = nodes[1].node.get_and_clear_pending_events();
7575                 assert_eq!(events_4.len(), 1);
7576                 match events_4[0] {
7577                         Event::PendingHTLCsForwardable { .. } => { },
7578                         _ => panic!("Unexpected event"),
7579                 };
7580
7581                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7582                 nodes[1].node.process_pending_htlc_forwards();
7583
7584                 let events_5 = nodes[1].node.get_and_clear_pending_events();
7585                 assert_eq!(events_5.len(), 1);
7586                 match events_5[0] {
7587                         Event::PaymentReceived { ref payment_hash, amt: _ } => {
7588                                 assert_eq!(payment_hash_2, *payment_hash);
7589                         },
7590                         _ => panic!("Unexpected event"),
7591                 }
7592
7593                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
7594                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7595                 check_added_monitors!(nodes[0], 1);
7596
7597                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7598         }
7599
7600         #[test]
7601         fn test_simple_monitor_permanent_update_fail() {
7602                 // Test that we handle a simple permanent monitor update failure
7603                 let mut nodes = create_network(2);
7604                 create_announced_chan_between_nodes(&nodes, 0, 1);
7605
7606                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7607                 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7608
7609                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7610                 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route, payment_hash_1) {} else { panic!(); }
7611                 check_added_monitors!(nodes[0], 1);
7612
7613                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7614                 assert_eq!(events_1.len(), 2);
7615                 match events_1[0] {
7616                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7617                         _ => panic!("Unexpected event"),
7618                 };
7619                 match events_1[1] {
7620                         MessageSendEvent::HandleError { node_id, .. } => assert_eq!(node_id, nodes[1].node.get_our_node_id()),
7621                         _ => panic!("Unexpected event"),
7622                 };
7623
7624                 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7625                 // PaymentFailed event
7626
7627                 assert_eq!(nodes[0].node.list_channels().len(), 0);
7628         }
7629
7630         fn do_test_simple_monitor_temporary_update_fail(disconnect: bool) {
7631                 // Test that we can recover from a simple temporary monitor update failure optionally with
7632                 // a disconnect in between
7633                 let mut nodes = create_network(2);
7634                 create_announced_chan_between_nodes(&nodes, 0, 1);
7635
7636                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7637                 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7638
7639                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7640                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_1) {} else { panic!(); }
7641                 check_added_monitors!(nodes[0], 1);
7642
7643                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7644                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7645                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7646
7647                 if disconnect {
7648                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7649                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7650                         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7651                 }
7652
7653                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7654                 nodes[0].node.test_restore_channel_monitor();
7655                 check_added_monitors!(nodes[0], 1);
7656
7657                 let mut events_2 = nodes[0].node.get_and_clear_pending_msg_events();
7658                 assert_eq!(events_2.len(), 1);
7659                 let payment_event = SendEvent::from_event(events_2.pop().unwrap());
7660                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7661                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7662                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7663
7664                 expect_pending_htlcs_forwardable!(nodes[1]);
7665
7666                 let events_3 = nodes[1].node.get_and_clear_pending_events();
7667                 assert_eq!(events_3.len(), 1);
7668                 match events_3[0] {
7669                         Event::PaymentReceived { ref payment_hash, amt } => {
7670                                 assert_eq!(payment_hash_1, *payment_hash);
7671                                 assert_eq!(amt, 1000000);
7672                         },
7673                         _ => panic!("Unexpected event"),
7674                 }
7675
7676                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_1);
7677
7678                 // Now set it to failed again...
7679                 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7680                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7681                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route, payment_hash_2) {} else { panic!(); }
7682                 check_added_monitors!(nodes[0], 1);
7683
7684                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7685                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7686                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7687
7688                 if disconnect {
7689                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7690                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7691                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7692                 }
7693
7694                 // ...and make sure we can force-close a TemporaryFailure channel with a PermanentFailure
7695                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7696                 nodes[0].node.test_restore_channel_monitor();
7697                 check_added_monitors!(nodes[0], 1);
7698
7699                 let events_5 = nodes[0].node.get_and_clear_pending_msg_events();
7700                 assert_eq!(events_5.len(), 1);
7701                 match events_5[0] {
7702                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7703                         _ => panic!("Unexpected event"),
7704                 }
7705
7706                 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7707                 // PaymentFailed event
7708
7709                 assert_eq!(nodes[0].node.list_channels().len(), 0);
7710         }
7711
7712         #[test]
7713         fn test_simple_monitor_temporary_update_fail() {
7714                 do_test_simple_monitor_temporary_update_fail(false);
7715                 do_test_simple_monitor_temporary_update_fail(true);
7716         }
7717
7718         fn do_test_monitor_temporary_update_fail(disconnect_count: usize) {
7719                 let disconnect_flags = 8 | 16;
7720
7721                 // Test that we can recover from a temporary monitor update failure with some in-flight
7722                 // HTLCs going on at the same time potentially with some disconnection thrown in.
7723                 // * First we route a payment, then get a temporary monitor update failure when trying to
7724                 //   route a second payment. We then claim the first payment.
7725                 // * If disconnect_count is set, we will disconnect at this point (which is likely as
7726                 //   TemporaryFailure likely indicates net disconnect which resulted in failing to update
7727                 //   the ChannelMonitor on a watchtower).
7728                 // * If !(disconnect_count & 16) we deliver a update_fulfill_htlc/CS for the first payment
7729                 //   immediately, otherwise we wait sconnect and deliver them via the reconnect
7730                 //   channel_reestablish processing (ie disconnect_count & 16 makes no sense if
7731                 //   disconnect_count & !disconnect_flags is 0).
7732                 // * We then update the channel monitor, reconnecting if disconnect_count is set and walk
7733                 //   through message sending, potentially disconnect/reconnecting multiple times based on
7734                 //   disconnect_count, to get the update_fulfill_htlc through.
7735                 // * We then walk through more message exchanges to get the original update_add_htlc
7736                 //   through, swapping message ordering based on disconnect_count & 8 and optionally
7737                 //   disconnect/reconnecting based on disconnect_count.
7738                 let mut nodes = create_network(2);
7739                 create_announced_chan_between_nodes(&nodes, 0, 1);
7740
7741                 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7742
7743                 // Now try to send a second payment which will fail to send
7744                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7745                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7746
7747                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7748                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_2) {} else { panic!(); }
7749                 check_added_monitors!(nodes[0], 1);
7750
7751                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7752                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7753                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7754
7755                 // Claim the previous payment, which will result in a update_fulfill_htlc/CS from nodes[1]
7756                 // but nodes[0] won't respond since it is frozen.
7757                 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7758                 check_added_monitors!(nodes[1], 1);
7759                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7760                 assert_eq!(events_2.len(), 1);
7761                 let (bs_initial_fulfill, bs_initial_commitment_signed) = match events_2[0] {
7762                         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 } } => {
7763                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7764                                 assert!(update_add_htlcs.is_empty());
7765                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7766                                 assert!(update_fail_htlcs.is_empty());
7767                                 assert!(update_fail_malformed_htlcs.is_empty());
7768                                 assert!(update_fee.is_none());
7769
7770                                 if (disconnect_count & 16) == 0 {
7771                                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7772                                         let events_3 = nodes[0].node.get_and_clear_pending_events();
7773                                         assert_eq!(events_3.len(), 1);
7774                                         match events_3[0] {
7775                                                 Event::PaymentSent { ref payment_preimage } => {
7776                                                         assert_eq!(*payment_preimage, payment_preimage_1);
7777                                                 },
7778                                                 _ => panic!("Unexpected event"),
7779                                         }
7780
7781                                         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) {
7782                                                 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
7783                                         } else { panic!(); }
7784                                 }
7785
7786                                 (update_fulfill_htlcs[0].clone(), commitment_signed.clone())
7787                         },
7788                         _ => panic!("Unexpected event"),
7789                 };
7790
7791                 if disconnect_count & !disconnect_flags > 0 {
7792                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7793                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7794                 }
7795
7796                 // Now fix monitor updating...
7797                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7798                 nodes[0].node.test_restore_channel_monitor();
7799                 check_added_monitors!(nodes[0], 1);
7800
7801                 macro_rules! disconnect_reconnect_peers { () => { {
7802                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7803                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7804
7805                         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7806                         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7807                         assert_eq!(reestablish_1.len(), 1);
7808                         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7809                         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7810                         assert_eq!(reestablish_2.len(), 1);
7811
7812                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7813                         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7814                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7815                         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7816
7817                         assert!(as_resp.0.is_none());
7818                         assert!(bs_resp.0.is_none());
7819
7820                         (reestablish_1, reestablish_2, as_resp, bs_resp)
7821                 } } }
7822
7823                 let (payment_event, initial_revoke_and_ack) = if disconnect_count & !disconnect_flags > 0 {
7824                         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7825                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7826
7827                         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7828                         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7829                         assert_eq!(reestablish_1.len(), 1);
7830                         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7831                         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7832                         assert_eq!(reestablish_2.len(), 1);
7833
7834                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7835                         check_added_monitors!(nodes[0], 0);
7836                         let mut as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7837                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7838                         check_added_monitors!(nodes[1], 0);
7839                         let mut bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7840
7841                         assert!(as_resp.0.is_none());
7842                         assert!(bs_resp.0.is_none());
7843
7844                         assert!(bs_resp.1.is_none());
7845                         if (disconnect_count & 16) == 0 {
7846                                 assert!(bs_resp.2.is_none());
7847
7848                                 assert!(as_resp.1.is_some());
7849                                 assert!(as_resp.2.is_some());
7850                                 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7851                         } else {
7852                                 assert!(bs_resp.2.as_ref().unwrap().update_add_htlcs.is_empty());
7853                                 assert!(bs_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7854                                 assert!(bs_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7855                                 assert!(bs_resp.2.as_ref().unwrap().update_fee.is_none());
7856                                 assert!(bs_resp.2.as_ref().unwrap().update_fulfill_htlcs == vec![bs_initial_fulfill]);
7857                                 assert!(bs_resp.2.as_ref().unwrap().commitment_signed == bs_initial_commitment_signed);
7858
7859                                 assert!(as_resp.1.is_none());
7860
7861                                 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();
7862                                 let events_3 = nodes[0].node.get_and_clear_pending_events();
7863                                 assert_eq!(events_3.len(), 1);
7864                                 match events_3[0] {
7865                                         Event::PaymentSent { ref payment_preimage } => {
7866                                                 assert_eq!(*payment_preimage, payment_preimage_1);
7867                                         },
7868                                         _ => panic!("Unexpected event"),
7869                                 }
7870
7871                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7872                                 let as_resp_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7873                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7874                                 check_added_monitors!(nodes[0], 1);
7875
7876                                 as_resp.1 = Some(as_resp_raa);
7877                                 bs_resp.2 = None;
7878                         }
7879
7880                         if disconnect_count & !disconnect_flags > 1 {
7881                                 let (second_reestablish_1, second_reestablish_2, second_as_resp, second_bs_resp) = disconnect_reconnect_peers!();
7882
7883                                 if (disconnect_count & 16) == 0 {
7884                                         assert!(reestablish_1 == second_reestablish_1);
7885                                         assert!(reestablish_2 == second_reestablish_2);
7886                                 }
7887                                 assert!(as_resp == second_as_resp);
7888                                 assert!(bs_resp == second_bs_resp);
7889                         }
7890
7891                         (SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), as_resp.2.unwrap()), as_resp.1.unwrap())
7892                 } else {
7893                         let mut events_4 = nodes[0].node.get_and_clear_pending_msg_events();
7894                         assert_eq!(events_4.len(), 2);
7895                         (SendEvent::from_event(events_4.remove(0)), match events_4[0] {
7896                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
7897                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7898                                         msg.clone()
7899                                 },
7900                                 _ => panic!("Unexpected event"),
7901                         })
7902                 };
7903
7904                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7905
7906                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7907                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7908                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7909                 // nodes[1] is awaiting an RAA from nodes[0] still so get_event_msg's assert(len == 1) passes
7910                 check_added_monitors!(nodes[1], 1);
7911
7912                 if disconnect_count & !disconnect_flags > 2 {
7913                         let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7914
7915                         assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7916                         assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7917
7918                         assert!(as_resp.2.is_none());
7919                         assert!(bs_resp.2.is_none());
7920                 }
7921
7922                 let as_commitment_update;
7923                 let bs_second_commitment_update;
7924
7925                 macro_rules! handle_bs_raa { () => {
7926                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7927                         as_commitment_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7928                         assert!(as_commitment_update.update_add_htlcs.is_empty());
7929                         assert!(as_commitment_update.update_fulfill_htlcs.is_empty());
7930                         assert!(as_commitment_update.update_fail_htlcs.is_empty());
7931                         assert!(as_commitment_update.update_fail_malformed_htlcs.is_empty());
7932                         assert!(as_commitment_update.update_fee.is_none());
7933                         check_added_monitors!(nodes[0], 1);
7934                 } }
7935
7936                 macro_rules! handle_initial_raa { () => {
7937                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &initial_revoke_and_ack).unwrap();
7938                         bs_second_commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7939                         assert!(bs_second_commitment_update.update_add_htlcs.is_empty());
7940                         assert!(bs_second_commitment_update.update_fulfill_htlcs.is_empty());
7941                         assert!(bs_second_commitment_update.update_fail_htlcs.is_empty());
7942                         assert!(bs_second_commitment_update.update_fail_malformed_htlcs.is_empty());
7943                         assert!(bs_second_commitment_update.update_fee.is_none());
7944                         check_added_monitors!(nodes[1], 1);
7945                 } }
7946
7947                 if (disconnect_count & 8) == 0 {
7948                         handle_bs_raa!();
7949
7950                         if disconnect_count & !disconnect_flags > 3 {
7951                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7952
7953                                 assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7954                                 assert!(bs_resp.1.is_none());
7955
7956                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7957                                 assert!(bs_resp.2.is_none());
7958
7959                                 assert!(as_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7960                         }
7961
7962                         handle_initial_raa!();
7963
7964                         if disconnect_count & !disconnect_flags > 4 {
7965                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7966
7967                                 assert!(as_resp.1.is_none());
7968                                 assert!(bs_resp.1.is_none());
7969
7970                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7971                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7972                         }
7973                 } else {
7974                         handle_initial_raa!();
7975
7976                         if disconnect_count & !disconnect_flags > 3 {
7977                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7978
7979                                 assert!(as_resp.1.is_none());
7980                                 assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7981
7982                                 assert!(as_resp.2.is_none());
7983                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7984
7985                                 assert!(bs_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7986                         }
7987
7988                         handle_bs_raa!();
7989
7990                         if disconnect_count & !disconnect_flags > 4 {
7991                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7992
7993                                 assert!(as_resp.1.is_none());
7994                                 assert!(bs_resp.1.is_none());
7995
7996                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7997                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7998                         }
7999                 }
8000
8001                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_update.commitment_signed).unwrap();
8002                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8003                 // No commitment_signed so get_event_msg's assert(len == 1) passes
8004                 check_added_monitors!(nodes[0], 1);
8005
8006                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_update.commitment_signed).unwrap();
8007                 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
8008                 // No commitment_signed so get_event_msg's assert(len == 1) passes
8009                 check_added_monitors!(nodes[1], 1);
8010
8011                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
8012                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8013                 check_added_monitors!(nodes[1], 1);
8014
8015                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
8016                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8017                 check_added_monitors!(nodes[0], 1);
8018
8019                 expect_pending_htlcs_forwardable!(nodes[1]);
8020
8021                 let events_5 = nodes[1].node.get_and_clear_pending_events();
8022                 assert_eq!(events_5.len(), 1);
8023                 match events_5[0] {
8024                         Event::PaymentReceived { ref payment_hash, amt } => {
8025                                 assert_eq!(payment_hash_2, *payment_hash);
8026                                 assert_eq!(amt, 1000000);
8027                         },
8028                         _ => panic!("Unexpected event"),
8029                 }
8030
8031                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
8032         }
8033
8034         #[test]
8035         fn test_monitor_temporary_update_fail_a() {
8036                 do_test_monitor_temporary_update_fail(0);
8037                 do_test_monitor_temporary_update_fail(1);
8038                 do_test_monitor_temporary_update_fail(2);
8039                 do_test_monitor_temporary_update_fail(3);
8040                 do_test_monitor_temporary_update_fail(4);
8041                 do_test_monitor_temporary_update_fail(5);
8042         }
8043
8044         #[test]
8045         fn test_monitor_temporary_update_fail_b() {
8046                 do_test_monitor_temporary_update_fail(2 | 8);
8047                 do_test_monitor_temporary_update_fail(3 | 8);
8048                 do_test_monitor_temporary_update_fail(4 | 8);
8049                 do_test_monitor_temporary_update_fail(5 | 8);
8050         }
8051
8052         #[test]
8053         fn test_monitor_temporary_update_fail_c() {
8054                 do_test_monitor_temporary_update_fail(1 | 16);
8055                 do_test_monitor_temporary_update_fail(2 | 16);
8056                 do_test_monitor_temporary_update_fail(3 | 16);
8057                 do_test_monitor_temporary_update_fail(2 | 8 | 16);
8058                 do_test_monitor_temporary_update_fail(3 | 8 | 16);
8059         }
8060
8061         #[test]
8062         fn test_monitor_update_fail_cs() {
8063                 // Tests handling of a monitor update failure when processing an incoming commitment_signed
8064                 let mut nodes = create_network(2);
8065                 create_announced_chan_between_nodes(&nodes, 0, 1);
8066
8067                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8068                 let (payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
8069                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
8070                 check_added_monitors!(nodes[0], 1);
8071
8072                 let send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8073                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8074
8075                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8076                 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() {
8077                         assert_eq!(err, "Failed to update ChannelMonitor");
8078                 } else { panic!(); }
8079                 check_added_monitors!(nodes[1], 1);
8080                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8081
8082                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8083                 nodes[1].node.test_restore_channel_monitor();
8084                 check_added_monitors!(nodes[1], 1);
8085                 let responses = nodes[1].node.get_and_clear_pending_msg_events();
8086                 assert_eq!(responses.len(), 2);
8087
8088                 match responses[0] {
8089                         MessageSendEvent::SendRevokeAndACK { ref msg, ref node_id } => {
8090                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8091                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &msg).unwrap();
8092                                 check_added_monitors!(nodes[0], 1);
8093                         },
8094                         _ => panic!("Unexpected event"),
8095                 }
8096                 match responses[1] {
8097                         MessageSendEvent::UpdateHTLCs { ref updates, ref node_id } => {
8098                                 assert!(updates.update_add_htlcs.is_empty());
8099                                 assert!(updates.update_fulfill_htlcs.is_empty());
8100                                 assert!(updates.update_fail_htlcs.is_empty());
8101                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8102                                 assert!(updates.update_fee.is_none());
8103                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8104
8105                                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8106                                 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() {
8107                                         assert_eq!(err, "Failed to update ChannelMonitor");
8108                                 } else { panic!(); }
8109                                 check_added_monitors!(nodes[0], 1);
8110                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8111                         },
8112                         _ => panic!("Unexpected event"),
8113                 }
8114
8115                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
8116                 nodes[0].node.test_restore_channel_monitor();
8117                 check_added_monitors!(nodes[0], 1);
8118
8119                 let final_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8120                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &final_raa).unwrap();
8121                 check_added_monitors!(nodes[1], 1);
8122
8123                 let mut events = nodes[1].node.get_and_clear_pending_events();
8124                 assert_eq!(events.len(), 1);
8125                 match events[0] {
8126                         Event::PendingHTLCsForwardable { .. } => { },
8127                         _ => panic!("Unexpected event"),
8128                 };
8129                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8130                 nodes[1].node.process_pending_htlc_forwards();
8131
8132                 events = nodes[1].node.get_and_clear_pending_events();
8133                 assert_eq!(events.len(), 1);
8134                 match events[0] {
8135                         Event::PaymentReceived { payment_hash, amt } => {
8136                                 assert_eq!(payment_hash, our_payment_hash);
8137                                 assert_eq!(amt, 1000000);
8138                         },
8139                         _ => panic!("Unexpected event"),
8140                 };
8141
8142                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
8143         }
8144
8145         fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) {
8146                 // Tests handling of a monitor update failure when processing an incoming RAA
8147                 let mut nodes = create_network(3);
8148                 create_announced_chan_between_nodes(&nodes, 0, 1);
8149                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
8150
8151                 // Rebalance a bit so that we can send backwards from 2 to 1.
8152                 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 5000000);
8153
8154                 // Route a first payment that we'll fail backwards
8155                 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
8156
8157                 // Fail the payment backwards, failing the monitor update on nodes[1]'s receipt of the RAA
8158                 assert!(nodes[2].node.fail_htlc_backwards(&payment_hash_1, PaymentFailReason::PreimageUnknown));
8159                 check_added_monitors!(nodes[2], 1);
8160
8161                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8162                 assert!(updates.update_add_htlcs.is_empty());
8163                 assert!(updates.update_fulfill_htlcs.is_empty());
8164                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8165                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8166                 assert!(updates.update_fee.is_none());
8167                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
8168
8169                 let bs_revoke_and_ack = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
8170                 check_added_monitors!(nodes[0], 0);
8171
8172                 // While the second channel is AwaitingRAA, forward a second payment to get it into the
8173                 // holding cell.
8174                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
8175                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8176                 nodes[0].node.send_payment(route, payment_hash_2).unwrap();
8177                 check_added_monitors!(nodes[0], 1);
8178
8179                 let mut send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8180                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8181                 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false);
8182
8183                 let events_1 = nodes[1].node.get_and_clear_pending_events();
8184                 assert_eq!(events_1.len(), 1);
8185                 match events_1[0] {
8186                         Event::PendingHTLCsForwardable { .. } => { },
8187                         _ => panic!("Unexpected event"),
8188                 };
8189
8190                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8191                 nodes[1].node.process_pending_htlc_forwards();
8192                 check_added_monitors!(nodes[1], 0);
8193                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8194
8195                 // Now fail monitor updating.
8196                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8197                 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() {
8198                         assert_eq!(err, "Failed to update ChannelMonitor");
8199                 } else { panic!(); }
8200                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8201                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8202                 check_added_monitors!(nodes[1], 1);
8203
8204                 // Attempt to forward a third payment but fail due to the second channel being unavailable
8205                 // for forwarding.
8206
8207                 let (_, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
8208                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8209                 nodes[0].node.send_payment(route, payment_hash_3).unwrap();
8210                 check_added_monitors!(nodes[0], 1);
8211
8212                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(()); // We succeed in updating the monitor for the first channel
8213                 send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8214                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8215                 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
8216                 check_added_monitors!(nodes[1], 0);
8217
8218                 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8219                 assert_eq!(events_2.len(), 1);
8220                 match events_2.remove(0) {
8221                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
8222                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8223                                 assert!(updates.update_fulfill_htlcs.is_empty());
8224                                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8225                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8226                                 assert!(updates.update_add_htlcs.is_empty());
8227                                 assert!(updates.update_fee.is_none());
8228
8229                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
8230                                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
8231
8232                                 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
8233                                 assert_eq!(msg_events.len(), 1);
8234                                 match msg_events[0] {
8235                                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
8236                                                 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
8237                                                 assert_eq!(msg.contents.flags & 2, 2); // temp disabled
8238                                         },
8239                                         _ => panic!("Unexpected event"),
8240                                 }
8241
8242                                 let events = nodes[0].node.get_and_clear_pending_events();
8243                                 assert_eq!(events.len(), 1);
8244                                 if let Event::PaymentFailed { payment_hash, rejected_by_dest, .. } = events[0] {
8245                                         assert_eq!(payment_hash, payment_hash_3);
8246                                         assert!(!rejected_by_dest);
8247                                 } else { panic!("Unexpected event!"); }
8248                         },
8249                         _ => panic!("Unexpected event type!"),
8250                 };
8251
8252                 let (payment_preimage_4, payment_hash_4) = if test_ignore_second_cs {
8253                         // Try to route another payment backwards from 2 to make sure 1 holds off on responding
8254                         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[0]);
8255                         let route = nodes[2].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8256                         nodes[2].node.send_payment(route, payment_hash_4).unwrap();
8257                         check_added_monitors!(nodes[2], 1);
8258
8259                         send_event = SendEvent::from_event(nodes[2].node.get_and_clear_pending_msg_events().remove(0));
8260                         nodes[1].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8261                         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) {
8262                                 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
8263                         } else { panic!(); }
8264                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8265                         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8266                         (Some(payment_preimage_4), Some(payment_hash_4))
8267                 } else { (None, None) };
8268
8269                 // Restore monitor updating, ensuring we immediately get a fail-back update and a
8270                 // update_add update.
8271                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8272                 nodes[1].node.test_restore_channel_monitor();
8273                 check_added_monitors!(nodes[1], 2);
8274
8275                 let mut events_3 = nodes[1].node.get_and_clear_pending_msg_events();
8276                 if test_ignore_second_cs {
8277                         assert_eq!(events_3.len(), 3);
8278                 } else {
8279                         assert_eq!(events_3.len(), 2);
8280                 }
8281
8282                 // Note that the ordering of the events for different nodes is non-prescriptive, though the
8283                 // ordering of the two events that both go to nodes[2] have to stay in the same order.
8284                 let messages_a = match events_3.pop().unwrap() {
8285                         MessageSendEvent::UpdateHTLCs { node_id, mut updates } => {
8286                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8287                                 assert!(updates.update_fulfill_htlcs.is_empty());
8288                                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8289                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8290                                 assert!(updates.update_add_htlcs.is_empty());
8291                                 assert!(updates.update_fee.is_none());
8292                                 (updates.update_fail_htlcs.remove(0), updates.commitment_signed)
8293                         },
8294                         _ => panic!("Unexpected event type!"),
8295                 };
8296                 let raa = if test_ignore_second_cs {
8297                         match events_3.remove(1) {
8298                                 MessageSendEvent::SendRevokeAndACK { node_id, msg } => {
8299                                         assert_eq!(node_id, nodes[2].node.get_our_node_id());
8300                                         Some(msg.clone())
8301                                 },
8302                                 _ => panic!("Unexpected event"),
8303                         }
8304                 } else { None };
8305                 let send_event_b = SendEvent::from_event(events_3.remove(0));
8306                 assert_eq!(send_event_b.node_id, nodes[2].node.get_our_node_id());
8307
8308                 // Now deliver the new messages...
8309
8310                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &messages_a.0).unwrap();
8311                 commitment_signed_dance!(nodes[0], nodes[1], messages_a.1, false);
8312                 let events_4 = nodes[0].node.get_and_clear_pending_events();
8313                 assert_eq!(events_4.len(), 1);
8314                 if let Event::PaymentFailed { payment_hash, rejected_by_dest, .. } = events_4[0] {
8315                         assert_eq!(payment_hash, payment_hash_1);
8316                         assert!(rejected_by_dest);
8317                 } else { panic!("Unexpected event!"); }
8318
8319                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event_b.msgs[0]).unwrap();
8320                 if test_ignore_second_cs {
8321                         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event_b.commitment_msg).unwrap();
8322                         check_added_monitors!(nodes[2], 1);
8323                         let bs_revoke_and_ack = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8324                         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa.unwrap()).unwrap();
8325                         check_added_monitors!(nodes[2], 1);
8326                         let bs_cs = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8327                         assert!(bs_cs.update_add_htlcs.is_empty());
8328                         assert!(bs_cs.update_fail_htlcs.is_empty());
8329                         assert!(bs_cs.update_fail_malformed_htlcs.is_empty());
8330                         assert!(bs_cs.update_fulfill_htlcs.is_empty());
8331                         assert!(bs_cs.update_fee.is_none());
8332
8333                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
8334                         check_added_monitors!(nodes[1], 1);
8335                         let as_cs = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
8336                         assert!(as_cs.update_add_htlcs.is_empty());
8337                         assert!(as_cs.update_fail_htlcs.is_empty());
8338                         assert!(as_cs.update_fail_malformed_htlcs.is_empty());
8339                         assert!(as_cs.update_fulfill_htlcs.is_empty());
8340                         assert!(as_cs.update_fee.is_none());
8341
8342                         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_cs.commitment_signed).unwrap();
8343                         check_added_monitors!(nodes[1], 1);
8344                         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
8345
8346                         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_cs.commitment_signed).unwrap();
8347                         check_added_monitors!(nodes[2], 1);
8348                         let bs_second_raa = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8349
8350                         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
8351                         check_added_monitors!(nodes[2], 1);
8352                         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
8353
8354                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_second_raa).unwrap();
8355                         check_added_monitors!(nodes[1], 1);
8356                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8357                 } else {
8358                         commitment_signed_dance!(nodes[2], nodes[1], send_event_b.commitment_msg, false);
8359                 }
8360
8361                 let events_5 = nodes[2].node.get_and_clear_pending_events();
8362                 assert_eq!(events_5.len(), 1);
8363                 match events_5[0] {
8364                         Event::PendingHTLCsForwardable { .. } => { },
8365                         _ => panic!("Unexpected event"),
8366                 };
8367
8368                 nodes[2].node.channel_state.lock().unwrap().next_forward = Instant::now();
8369                 nodes[2].node.process_pending_htlc_forwards();
8370
8371                 let events_6 = nodes[2].node.get_and_clear_pending_events();
8372                 assert_eq!(events_6.len(), 1);
8373                 match events_6[0] {
8374                         Event::PaymentReceived { payment_hash, .. } => { assert_eq!(payment_hash, payment_hash_2); },
8375                         _ => panic!("Unexpected event"),
8376                 };
8377
8378                 if test_ignore_second_cs {
8379                         let events_7 = nodes[1].node.get_and_clear_pending_events();
8380                         assert_eq!(events_7.len(), 1);
8381                         match events_7[0] {
8382                                 Event::PendingHTLCsForwardable { .. } => { },
8383                                 _ => panic!("Unexpected event"),
8384                         };
8385
8386                         nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8387                         nodes[1].node.process_pending_htlc_forwards();
8388                         check_added_monitors!(nodes[1], 1);
8389
8390                         send_event = SendEvent::from_node(&nodes[1]);
8391                         assert_eq!(send_event.node_id, nodes[0].node.get_our_node_id());
8392                         assert_eq!(send_event.msgs.len(), 1);
8393                         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8394                         commitment_signed_dance!(nodes[0], nodes[1], send_event.commitment_msg, false);
8395
8396                         let events_8 = nodes[0].node.get_and_clear_pending_events();
8397                         assert_eq!(events_8.len(), 1);
8398                         match events_8[0] {
8399                                 Event::PendingHTLCsForwardable { .. } => { },
8400                                 _ => panic!("Unexpected event"),
8401                         };
8402
8403                         nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
8404                         nodes[0].node.process_pending_htlc_forwards();
8405
8406                         let events_9 = nodes[0].node.get_and_clear_pending_events();
8407                         assert_eq!(events_9.len(), 1);
8408                         match events_9[0] {
8409                                 Event::PaymentReceived { payment_hash, .. } => assert_eq!(payment_hash, payment_hash_4.unwrap()),
8410                                 _ => panic!("Unexpected event"),
8411                         };
8412                         claim_payment(&nodes[2], &[&nodes[1], &nodes[0]], payment_preimage_4.unwrap());
8413                 }
8414
8415                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
8416         }
8417
8418         #[test]
8419         fn test_monitor_update_fail_raa() {
8420                 do_test_monitor_update_fail_raa(false);
8421                 do_test_monitor_update_fail_raa(true);
8422         }
8423
8424         #[test]
8425         fn test_monitor_update_fail_reestablish() {
8426                 // Simple test for message retransmission after monitor update failure on
8427                 // channel_reestablish generating a monitor update (which comes from freeing holding cell
8428                 // HTLCs).
8429                 let mut nodes = create_network(3);
8430                 create_announced_chan_between_nodes(&nodes, 0, 1);
8431                 create_announced_chan_between_nodes(&nodes, 1, 2);
8432
8433                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
8434
8435                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8436                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8437
8438                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
8439                 check_added_monitors!(nodes[2], 1);
8440                 let mut updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8441                 assert!(updates.update_add_htlcs.is_empty());
8442                 assert!(updates.update_fail_htlcs.is_empty());
8443                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8444                 assert!(updates.update_fee.is_none());
8445                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8446                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8447                 check_added_monitors!(nodes[1], 1);
8448                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8449                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
8450
8451                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8452                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8453                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8454
8455                 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
8456                 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8457
8458                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
8459
8460                 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() {
8461                         assert_eq!(err, "Failed to update ChannelMonitor");
8462                 } else { panic!(); }
8463                 check_added_monitors!(nodes[1], 1);
8464
8465                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8466                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8467
8468                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8469                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8470
8471                 assert!(as_reestablish == get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()));
8472                 assert!(bs_reestablish == get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id()));
8473
8474                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
8475
8476                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish).unwrap();
8477                 check_added_monitors!(nodes[1], 0);
8478                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8479
8480                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8481                 nodes[1].node.test_restore_channel_monitor();
8482                 check_added_monitors!(nodes[1], 1);
8483
8484                 updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8485                 assert!(updates.update_add_htlcs.is_empty());
8486                 assert!(updates.update_fail_htlcs.is_empty());
8487                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8488                 assert!(updates.update_fee.is_none());
8489                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8490                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8491                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
8492
8493                 let events = nodes[0].node.get_and_clear_pending_events();
8494                 assert_eq!(events.len(), 1);
8495                 match events[0] {
8496                         Event::PaymentSent { payment_preimage, .. } => assert_eq!(payment_preimage, our_payment_preimage),
8497                         _ => panic!("Unexpected event"),
8498                 }
8499         }
8500
8501         #[test]
8502         fn test_invalid_channel_announcement() {
8503                 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
8504                 let secp_ctx = Secp256k1::new();
8505                 let nodes = create_network(2);
8506
8507                 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1]);
8508
8509                 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8510                 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
8511                 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
8512                 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
8513
8514                 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 } );
8515
8516                 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
8517                 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
8518
8519                 let as_network_key = nodes[0].node.get_our_node_id();
8520                 let bs_network_key = nodes[1].node.get_our_node_id();
8521
8522                 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
8523
8524                 let mut chan_announcement;
8525
8526                 macro_rules! dummy_unsigned_msg {
8527                         () => {
8528                                 msgs::UnsignedChannelAnnouncement {
8529                                         features: msgs::GlobalFeatures::new(),
8530                                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
8531                                         short_channel_id: as_chan.get_short_channel_id().unwrap(),
8532                                         node_id_1: if were_node_one { as_network_key } else { bs_network_key },
8533                                         node_id_2: if were_node_one { bs_network_key } else { as_network_key },
8534                                         bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
8535                                         bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
8536                                         excess_data: Vec::new(),
8537                                 };
8538                         }
8539                 }
8540
8541                 macro_rules! sign_msg {
8542                         ($unsigned_msg: expr) => {
8543                                 let msghash = Message::from_slice(&Sha256dHash::from_data(&$unsigned_msg.encode()[..])[..]).unwrap();
8544                                 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
8545                                 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
8546                                 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].node.our_network_key);
8547                                 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].node.our_network_key);
8548                                 chan_announcement = msgs::ChannelAnnouncement {
8549                                         node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
8550                                         node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
8551                                         bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
8552                                         bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
8553                                         contents: $unsigned_msg
8554                                 }
8555                         }
8556                 }
8557
8558                 let unsigned_msg = dummy_unsigned_msg!();
8559                 sign_msg!(unsigned_msg);
8560                 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
8561                 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 } );
8562
8563                 // Configured with Network::Testnet
8564                 let mut unsigned_msg = dummy_unsigned_msg!();
8565                 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
8566                 sign_msg!(unsigned_msg);
8567                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
8568
8569                 let mut unsigned_msg = dummy_unsigned_msg!();
8570                 unsigned_msg.chain_hash = Sha256dHash::from_data(&[1,2,3,4,5,6,7,8,9]);
8571                 sign_msg!(unsigned_msg);
8572                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
8573         }
8574
8575         struct VecWriter(Vec<u8>);
8576         impl Writer for VecWriter {
8577                 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
8578                         self.0.extend_from_slice(buf);
8579                         Ok(())
8580                 }
8581                 fn size_hint(&mut self, size: usize) {
8582                         self.0.reserve_exact(size);
8583                 }
8584         }
8585
8586         #[test]
8587         fn test_no_txn_manager_serialize_deserialize() {
8588                 let mut nodes = create_network(2);
8589
8590                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
8591
8592                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8593
8594                 let nodes_0_serialized = nodes[0].node.encode();
8595                 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8596                 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8597
8598                 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())));
8599                 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8600                 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8601                 assert!(chan_0_monitor_read.is_empty());
8602
8603                 let mut nodes_0_read = &nodes_0_serialized[..];
8604                 let config = UserConfig::new();
8605                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8606                 let (_, nodes_0_deserialized) = {
8607                         let mut channel_monitors = HashMap::new();
8608                         channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8609                         <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8610                                 default_config: config,
8611                                 keys_manager,
8612                                 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8613                                 monitor: nodes[0].chan_monitor.clone(),
8614                                 chain_monitor: nodes[0].chain_monitor.clone(),
8615                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8616                                 logger: Arc::new(test_utils::TestLogger::new()),
8617                                 channel_monitors: &channel_monitors,
8618                         }).unwrap()
8619                 };
8620                 assert!(nodes_0_read.is_empty());
8621
8622                 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8623                 nodes[0].node = Arc::new(nodes_0_deserialized);
8624                 let nodes_0_as_listener: Arc<ChainListener> = nodes[0].node.clone();
8625                 nodes[0].chain_monitor.register_listener(Arc::downgrade(&nodes_0_as_listener));
8626                 assert_eq!(nodes[0].node.list_channels().len(), 1);
8627                 check_added_monitors!(nodes[0], 1);
8628
8629                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8630                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
8631                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8632                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
8633
8634                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
8635                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8636                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
8637                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8638
8639                 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8640                 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8641                 for node in nodes.iter() {
8642                         assert!(node.router.handle_channel_announcement(&announcement).unwrap());
8643                         node.router.handle_channel_update(&as_update).unwrap();
8644                         node.router.handle_channel_update(&bs_update).unwrap();
8645                 }
8646
8647                 send_payment(&nodes[0], &[&nodes[1]], 1000000);
8648         }
8649
8650         #[test]
8651         fn test_simple_manager_serialize_deserialize() {
8652                 let mut nodes = create_network(2);
8653                 create_announced_chan_between_nodes(&nodes, 0, 1);
8654
8655                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8656                 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8657
8658                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8659
8660                 let nodes_0_serialized = nodes[0].node.encode();
8661                 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8662                 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8663
8664                 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())));
8665                 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8666                 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8667                 assert!(chan_0_monitor_read.is_empty());
8668
8669                 let mut nodes_0_read = &nodes_0_serialized[..];
8670                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8671                 let (_, nodes_0_deserialized) = {
8672                         let mut channel_monitors = HashMap::new();
8673                         channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8674                         <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8675                                 default_config: UserConfig::new(),
8676                                 keys_manager,
8677                                 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8678                                 monitor: nodes[0].chan_monitor.clone(),
8679                                 chain_monitor: nodes[0].chain_monitor.clone(),
8680                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8681                                 logger: Arc::new(test_utils::TestLogger::new()),
8682                                 channel_monitors: &channel_monitors,
8683                         }).unwrap()
8684                 };
8685                 assert!(nodes_0_read.is_empty());
8686
8687                 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8688                 nodes[0].node = Arc::new(nodes_0_deserialized);
8689                 check_added_monitors!(nodes[0], 1);
8690
8691                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8692
8693                 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
8694                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
8695         }
8696
8697         #[test]
8698         fn test_manager_serialize_deserialize_inconsistent_monitor() {
8699                 // Test deserializing a ChannelManager with a out-of-date ChannelMonitor
8700                 let mut nodes = create_network(4);
8701                 create_announced_chan_between_nodes(&nodes, 0, 1);
8702                 create_announced_chan_between_nodes(&nodes, 2, 0);
8703                 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3);
8704
8705                 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
8706
8707                 // Serialize the ChannelManager here, but the monitor we keep up-to-date
8708                 let nodes_0_serialized = nodes[0].node.encode();
8709
8710                 route_payment(&nodes[0], &[&nodes[3]], 1000000);
8711                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8712                 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8713                 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8714
8715                 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
8716                 // nodes[3])
8717                 let mut node_0_monitors_serialized = Vec::new();
8718                 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
8719                         let mut writer = VecWriter(Vec::new());
8720                         monitor.1.write_for_disk(&mut writer).unwrap();
8721                         node_0_monitors_serialized.push(writer.0);
8722                 }
8723
8724                 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())));
8725                 let mut node_0_monitors = Vec::new();
8726                 for serialized in node_0_monitors_serialized.iter() {
8727                         let mut read = &serialized[..];
8728                         let (_, monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
8729                         assert!(read.is_empty());
8730                         node_0_monitors.push(monitor);
8731                 }
8732
8733                 let mut nodes_0_read = &nodes_0_serialized[..];
8734                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8735                 let (_, nodes_0_deserialized) = <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8736                         default_config: UserConfig::new(),
8737                         keys_manager,
8738                         fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8739                         monitor: nodes[0].chan_monitor.clone(),
8740                         chain_monitor: nodes[0].chain_monitor.clone(),
8741                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8742                         logger: Arc::new(test_utils::TestLogger::new()),
8743                         channel_monitors: &node_0_monitors.iter().map(|monitor| { (monitor.get_funding_txo().unwrap(), monitor) }).collect(),
8744                 }).unwrap();
8745                 assert!(nodes_0_read.is_empty());
8746
8747                 { // Channel close should result in a commitment tx and an HTLC tx
8748                         let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8749                         assert_eq!(txn.len(), 2);
8750                         assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
8751                         assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
8752                 }
8753
8754                 for monitor in node_0_monitors.drain(..) {
8755                         assert!(nodes[0].chan_monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor).is_ok());
8756                         check_added_monitors!(nodes[0], 1);
8757                 }
8758                 nodes[0].node = Arc::new(nodes_0_deserialized);
8759
8760                 // nodes[1] and nodes[2] have no lost state with nodes[0]...
8761                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8762                 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8763                 //... and we can even still claim the payment!
8764                 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
8765
8766                 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id());
8767                 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8768                 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id());
8769                 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) {
8770                         assert_eq!(msg.channel_id, channel_id);
8771                 } else { panic!("Unexpected result"); }
8772         }
8773
8774         macro_rules! check_spendable_outputs {
8775                 ($node: expr, $der_idx: expr) => {
8776                         {
8777                                 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
8778                                 let mut txn = Vec::new();
8779                                 for event in events {
8780                                         match event {
8781                                                 Event::SpendableOutputs { ref outputs } => {
8782                                                         for outp in outputs {
8783                                                                 match *outp {
8784                                                                         SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
8785                                                                                 let input = TxIn {
8786                                                                                         previous_output: outpoint.clone(),
8787                                                                                         script_sig: Script::new(),
8788                                                                                         sequence: 0,
8789                                                                                         witness: Vec::new(),
8790                                                                                 };
8791                                                                                 let outp = TxOut {
8792                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8793                                                                                         value: output.value,
8794                                                                                 };
8795                                                                                 let mut spend_tx = Transaction {
8796                                                                                         version: 2,
8797                                                                                         lock_time: 0,
8798                                                                                         input: vec![input],
8799                                                                                         output: vec![outp],
8800                                                                                 };
8801                                                                                 let secp_ctx = Secp256k1::new();
8802                                                                                 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
8803                                                                                 let witness_script = Address::p2pkh(&remotepubkey, Network::Testnet).script_pubkey();
8804                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8805                                                                                 let remotesig = secp_ctx.sign(&sighash, key);
8806                                                                                 spend_tx.input[0].witness.push(remotesig.serialize_der(&secp_ctx).to_vec());
8807                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8808                                                                                 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
8809                                                                                 txn.push(spend_tx);
8810                                                                         },
8811                                                                         SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
8812                                                                                 let input = TxIn {
8813                                                                                         previous_output: outpoint.clone(),
8814                                                                                         script_sig: Script::new(),
8815                                                                                         sequence: *to_self_delay as u32,
8816                                                                                         witness: Vec::new(),
8817                                                                                 };
8818                                                                                 let outp = TxOut {
8819                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8820                                                                                         value: output.value,
8821                                                                                 };
8822                                                                                 let mut spend_tx = Transaction {
8823                                                                                         version: 2,
8824                                                                                         lock_time: 0,
8825                                                                                         input: vec![input],
8826                                                                                         output: vec![outp],
8827                                                                                 };
8828                                                                                 let secp_ctx = Secp256k1::new();
8829                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
8830                                                                                 let local_delaysig = secp_ctx.sign(&sighash, key);
8831                                                                                 spend_tx.input[0].witness.push(local_delaysig.serialize_der(&secp_ctx).to_vec());
8832                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8833                                                                                 spend_tx.input[0].witness.push(vec!(0));
8834                                                                                 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
8835                                                                                 txn.push(spend_tx);
8836                                                                         },
8837                                                                         SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
8838                                                                                 let secp_ctx = Secp256k1::new();
8839                                                                                 let input = TxIn {
8840                                                                                         previous_output: outpoint.clone(),
8841                                                                                         script_sig: Script::new(),
8842                                                                                         sequence: 0,
8843                                                                                         witness: Vec::new(),
8844                                                                                 };
8845                                                                                 let outp = TxOut {
8846                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8847                                                                                         value: output.value,
8848                                                                                 };
8849                                                                                 let mut spend_tx = Transaction {
8850                                                                                         version: 2,
8851                                                                                         lock_time: 0,
8852                                                                                         input: vec![input],
8853                                                                                         output: vec![outp.clone()],
8854                                                                                 };
8855                                                                                 let secret = {
8856                                                                                         match ExtendedPrivKey::new_master(&secp_ctx, Network::Testnet, &$node.node_seed) {
8857                                                                                                 Ok(master_key) => {
8858                                                                                                         match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx)) {
8859                                                                                                                 Ok(key) => key,
8860                                                                                                                 Err(_) => panic!("Your RNG is busted"),
8861                                                                                                         }
8862                                                                                                 }
8863                                                                                                 Err(_) => panic!("Your rng is busted"),
8864                                                                                         }
8865                                                                                 };
8866                                                                                 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
8867                                                                                 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
8868                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8869                                                                                 let sig = secp_ctx.sign(&sighash, &secret.secret_key);
8870                                                                                 spend_tx.input[0].witness.push(sig.serialize_der(&secp_ctx).to_vec());
8871                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8872                                                                                 spend_tx.input[0].witness.push(pubkey.serialize().to_vec());
8873                                                                                 txn.push(spend_tx);
8874                                                                         },
8875                                                                 }
8876                                                         }
8877                                                 },
8878                                                 _ => panic!("Unexpected event"),
8879                                         };
8880                                 }
8881                                 txn
8882                         }
8883                 }
8884         }
8885
8886         #[test]
8887         fn test_claim_sizeable_push_msat() {
8888                 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
8889                 let nodes = create_network(2);
8890
8891                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8892                 nodes[1].node.force_close_channel(&chan.2);
8893                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8894                 match events[0] {
8895                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8896                         _ => panic!("Unexpected event"),
8897                 }
8898                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8899                 assert_eq!(node_txn.len(), 1);
8900                 check_spends!(node_txn[0], chan.3.clone());
8901                 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
8902
8903                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8904                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8905                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8906                 assert_eq!(spend_txn.len(), 1);
8907                 check_spends!(spend_txn[0], node_txn[0].clone());
8908         }
8909
8910         #[test]
8911         fn test_claim_on_remote_sizeable_push_msat() {
8912                 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8913                 // to_remote output is encumbered by a P2WPKH
8914
8915                 let nodes = create_network(2);
8916
8917                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8918                 nodes[0].node.force_close_channel(&chan.2);
8919                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8920                 match events[0] {
8921                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8922                         _ => panic!("Unexpected event"),
8923                 }
8924                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8925                 assert_eq!(node_txn.len(), 1);
8926                 check_spends!(node_txn[0], chan.3.clone());
8927                 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
8928
8929                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8930                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8931                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8932                 match events[0] {
8933                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8934                         _ => panic!("Unexpected event"),
8935                 }
8936                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8937                 assert_eq!(spend_txn.len(), 2);
8938                 assert_eq!(spend_txn[0], spend_txn[1]);
8939                 check_spends!(spend_txn[0], node_txn[0].clone());
8940         }
8941
8942         #[test]
8943         fn test_claim_on_remote_revoked_sizeable_push_msat() {
8944                 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8945                 // to_remote output is encumbered by a P2WPKH
8946
8947                 let nodes = create_network(2);
8948
8949                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
8950                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8951                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
8952                 assert_eq!(revoked_local_txn[0].input.len(), 1);
8953                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8954
8955                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8956                 let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8957                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
8958                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8959                 match events[0] {
8960                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8961                         _ => panic!("Unexpected event"),
8962                 }
8963                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8964                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8965                 assert_eq!(spend_txn.len(), 4);
8966                 assert_eq!(spend_txn[0], spend_txn[2]); // to_remote output on revoked remote commitment_tx
8967                 check_spends!(spend_txn[0], revoked_local_txn[0].clone());
8968                 assert_eq!(spend_txn[1], spend_txn[3]); // to_local output on local commitment tx
8969                 check_spends!(spend_txn[1], node_txn[0].clone());
8970         }
8971
8972         #[test]
8973         fn test_static_spendable_outputs_preimage_tx() {
8974                 let nodes = create_network(2);
8975
8976                 // Create some initial channels
8977                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8978
8979                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8980
8981                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8982                 assert_eq!(commitment_tx[0].input.len(), 1);
8983                 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
8984
8985                 // Settle A's commitment tx on B's chain
8986                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8987                 assert!(nodes[1].node.claim_funds(payment_preimage));
8988                 check_added_monitors!(nodes[1], 1);
8989                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
8990                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8991                 match events[0] {
8992                         MessageSendEvent::UpdateHTLCs { .. } => {},
8993                         _ => panic!("Unexpected event"),
8994                 }
8995                 match events[1] {
8996                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8997                         _ => panic!("Unexepected event"),
8998                 }
8999
9000                 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
9001                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 1 (local commitment tx), ChannelMonitor: 2 (1 preimage tx) * 2 (block-rescan)
9002                 check_spends!(node_txn[0], commitment_tx[0].clone());
9003                 assert_eq!(node_txn[0], node_txn[2]);
9004                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9005                 check_spends!(node_txn[1], chan_1.3.clone());
9006
9007                 let spend_txn = check_spendable_outputs!(nodes[1], 1); // , 0, 0, 1, 1);
9008                 assert_eq!(spend_txn.len(), 2);
9009                 assert_eq!(spend_txn[0], spend_txn[1]);
9010                 check_spends!(spend_txn[0], node_txn[0].clone());
9011         }
9012
9013         #[test]
9014         fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
9015                 let nodes = create_network(2);
9016
9017                 // Create some initial channels
9018                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9019
9020                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9021                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
9022                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9023                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9024
9025                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9026
9027                 let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9028                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9029                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9030                 match events[0] {
9031                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9032                         _ => panic!("Unexpected event"),
9033                 }
9034                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9035                 assert_eq!(node_txn.len(), 3);
9036                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]);
9037                 assert_eq!(node_txn[0].input.len(), 2);
9038                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
9039
9040                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9041                 assert_eq!(spend_txn.len(), 2);
9042                 assert_eq!(spend_txn[0], spend_txn[1]);
9043                 check_spends!(spend_txn[0], node_txn[0].clone());
9044         }
9045
9046         #[test]
9047         fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
9048                 let nodes = create_network(2);
9049
9050                 // Create some initial channels
9051                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9052
9053                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9054                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9055                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9056                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9057
9058                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9059
9060                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9061                 // A will generate HTLC-Timeout from revoked commitment tx
9062                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9063                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9064                 match events[0] {
9065                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9066                         _ => panic!("Unexpected event"),
9067                 }
9068                 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9069                 assert_eq!(revoked_htlc_txn.len(), 3);
9070                 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
9071                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
9072                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9073                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
9074                 check_spends!(revoked_htlc_txn[1], chan_1.3.clone());
9075
9076                 // B will generate justice tx from A's revoked commitment/HTLC tx
9077                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
9078                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9079                 match events[0] {
9080                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9081                         _ => panic!("Unexpected event"),
9082                 }
9083
9084                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9085                 assert_eq!(node_txn.len(), 4);
9086                 assert_eq!(node_txn[3].input.len(), 1);
9087                 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
9088
9089                 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
9090                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9091                 assert_eq!(spend_txn.len(), 3);
9092                 assert_eq!(spend_txn[0], spend_txn[1]);
9093                 check_spends!(spend_txn[0], node_txn[0].clone());
9094                 check_spends!(spend_txn[2], node_txn[3].clone());
9095         }
9096
9097         #[test]
9098         fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
9099                 let nodes = create_network(2);
9100
9101                 // Create some initial channels
9102                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9103
9104                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9105                 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9106                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9107                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9108
9109                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9110
9111                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9112                 // B will generate HTLC-Success from revoked commitment tx
9113                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9114                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9115                 match events[0] {
9116                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9117                         _ => panic!("Unexpected event"),
9118                 }
9119                 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9120
9121                 assert_eq!(revoked_htlc_txn.len(), 3);
9122                 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
9123                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
9124                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9125                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
9126
9127                 // A will generate justice tx from B's revoked commitment/HTLC tx
9128                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
9129                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9130                 match events[0] {
9131                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9132                         _ => panic!("Unexpected event"),
9133                 }
9134
9135                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9136                 assert_eq!(node_txn.len(), 4);
9137                 assert_eq!(node_txn[3].input.len(), 1);
9138                 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
9139
9140                 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
9141                 let spend_txn = check_spendable_outputs!(nodes[0], 1);
9142                 assert_eq!(spend_txn.len(), 5);
9143                 assert_eq!(spend_txn[0], spend_txn[2]);
9144                 assert_eq!(spend_txn[1], spend_txn[3]);
9145                 check_spends!(spend_txn[0], revoked_local_txn[0].clone()); // spending to_remote output from revoked local tx
9146                 check_spends!(spend_txn[1], node_txn[2].clone()); // spending justice tx output from revoked local tx htlc received output
9147                 check_spends!(spend_txn[4], node_txn[3].clone()); // spending justice tx output on htlc success tx
9148         }
9149
9150         #[test]
9151         fn test_onchain_to_onchain_claim() {
9152                 // Test that in case of channel closure, we detect the state of output thanks to
9153                 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
9154                 // First, have C claim an HTLC against its own latest commitment transaction.
9155                 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
9156                 // channel.
9157                 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
9158                 // gets broadcast.
9159
9160                 let nodes = create_network(3);
9161
9162                 // Create some initial channels
9163                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9164                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
9165
9166                 // Rebalance the network a bit by relaying one payment through all the channels ...
9167                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
9168                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
9169
9170                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
9171                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9172                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
9173                 check_spends!(commitment_tx[0], chan_2.3.clone());
9174                 nodes[2].node.claim_funds(payment_preimage);
9175                 check_added_monitors!(nodes[2], 1);
9176                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9177                 assert!(updates.update_add_htlcs.is_empty());
9178                 assert!(updates.update_fail_htlcs.is_empty());
9179                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
9180                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9181
9182                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
9183                 let events = nodes[2].node.get_and_clear_pending_msg_events();
9184                 assert_eq!(events.len(), 1);
9185                 match events[0] {
9186                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9187                         _ => panic!("Unexpected event"),
9188                 }
9189
9190                 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
9191                 assert_eq!(c_txn.len(), 3);
9192                 assert_eq!(c_txn[0], c_txn[2]);
9193                 assert_eq!(commitment_tx[0], c_txn[1]);
9194                 check_spends!(c_txn[1], chan_2.3.clone());
9195                 check_spends!(c_txn[2], c_txn[1].clone());
9196                 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
9197                 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9198                 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
9199                 assert_eq!(c_txn[0].lock_time, 0); // Success tx
9200
9201                 // 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
9202                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
9203                 {
9204                         let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9205                         assert_eq!(b_txn.len(), 4);
9206                         assert_eq!(b_txn[0], b_txn[3]);
9207                         check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
9208                         check_spends!(b_txn[2], b_txn[1].clone()); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
9209                         assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9210                         assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
9211                         assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
9212                         check_spends!(b_txn[0], c_txn[1].clone()); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
9213                         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9214                         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
9215                         assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
9216                         b_txn.clear();
9217                 }
9218                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
9219                 check_added_monitors!(nodes[1], 1);
9220                 match msg_events[0] {
9221                         MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
9222                         _ => panic!("Unexpected event"),
9223                 }
9224                 match msg_events[1] {
9225                         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, .. } } => {
9226                                 assert!(update_add_htlcs.is_empty());
9227                                 assert!(update_fail_htlcs.is_empty());
9228                                 assert_eq!(update_fulfill_htlcs.len(), 1);
9229                                 assert!(update_fail_malformed_htlcs.is_empty());
9230                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
9231                         },
9232                         _ => panic!("Unexpected event"),
9233                 };
9234                 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
9235                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9236                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
9237                 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9238                 assert_eq!(b_txn.len(), 3);
9239                 check_spends!(b_txn[1], chan_1.3); // Local commitment tx, issued by ChannelManager
9240                 assert_eq!(b_txn[0], b_txn[2]); // HTLC-Success tx, issued by ChannelMonitor, * 2 due to block rescan
9241                 check_spends!(b_txn[0], commitment_tx[0].clone());
9242                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9243                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
9244                 assert_eq!(b_txn[2].lock_time, 0); // Success tx
9245                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
9246                 match msg_events[0] {
9247                         MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
9248                         _ => panic!("Unexpected event"),
9249                 }
9250         }
9251
9252         #[test]
9253         fn test_duplicate_payment_hash_one_failure_one_success() {
9254                 // Topology : A --> B --> C
9255                 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
9256                 let mut nodes = create_network(3);
9257
9258                 create_announced_chan_between_nodes(&nodes, 0, 1);
9259                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
9260
9261                 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
9262                 *nodes[0].network_payment_count.borrow_mut() -= 1;
9263                 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
9264
9265                 let commitment_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
9266                 assert_eq!(commitment_txn[0].input.len(), 1);
9267                 check_spends!(commitment_txn[0], chan_2.3.clone());
9268
9269                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9270                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
9271                 let htlc_timeout_tx;
9272                 { // Extract one of the two HTLC-Timeout transaction
9273                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9274                         assert_eq!(node_txn.len(), 7);
9275                         assert_eq!(node_txn[0], node_txn[5]);
9276                         assert_eq!(node_txn[1], node_txn[6]);
9277                         check_spends!(node_txn[0], commitment_txn[0].clone());
9278                         assert_eq!(node_txn[0].input.len(), 1);
9279                         check_spends!(node_txn[1], commitment_txn[0].clone());
9280                         assert_eq!(node_txn[1].input.len(), 1);
9281                         assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
9282                         check_spends!(node_txn[2], chan_2.3.clone());
9283                         check_spends!(node_txn[3], node_txn[2].clone());
9284                         check_spends!(node_txn[4], node_txn[2].clone());
9285                         htlc_timeout_tx = node_txn[1].clone();
9286                 }
9287
9288                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9289                 match events[0] {
9290                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9291                         _ => panic!("Unexepected event"),
9292                 }
9293
9294                 nodes[2].node.claim_funds(our_payment_preimage);
9295                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
9296                 check_added_monitors!(nodes[2], 2);
9297                 let events = nodes[2].node.get_and_clear_pending_msg_events();
9298                 match events[0] {
9299                         MessageSendEvent::UpdateHTLCs { .. } => {},
9300                         _ => panic!("Unexpected event"),
9301                 }
9302                 match events[1] {
9303                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9304                         _ => panic!("Unexepected event"),
9305                 }
9306                 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9307                 assert_eq!(htlc_success_txn.len(), 5);
9308                 check_spends!(htlc_success_txn[2], chan_2.3.clone());
9309                 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
9310                 assert_eq!(htlc_success_txn[0].input.len(), 1);
9311                 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9312                 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
9313                 assert_eq!(htlc_success_txn[1].input.len(), 1);
9314                 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9315                 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
9316                 check_spends!(htlc_success_txn[0], commitment_txn[0].clone());
9317                 check_spends!(htlc_success_txn[1], commitment_txn[0].clone());
9318
9319                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
9320                 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9321                 assert!(htlc_updates.update_add_htlcs.is_empty());
9322                 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
9323                 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
9324                 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
9325                 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
9326                 check_added_monitors!(nodes[1], 1);
9327
9328                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]).unwrap();
9329                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9330                 {
9331                         commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
9332                         let events = nodes[0].node.get_and_clear_pending_msg_events();
9333                         assert_eq!(events.len(), 1);
9334                         match events[0] {
9335                                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
9336                                 },
9337                                 _ => { panic!("Unexpected event"); }
9338                         }
9339                 }
9340                 let events = nodes[0].node.get_and_clear_pending_events();
9341                 match events[0] {
9342                         Event::PaymentFailed { ref payment_hash, .. } => {
9343                                 assert_eq!(*payment_hash, duplicate_payment_hash);
9344                         }
9345                         _ => panic!("Unexpected event"),
9346                 }
9347
9348                 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
9349                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
9350                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9351                 assert!(updates.update_add_htlcs.is_empty());
9352                 assert!(updates.update_fail_htlcs.is_empty());
9353                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
9354                 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
9355                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9356                 check_added_monitors!(nodes[1], 1);
9357
9358                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
9359                 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
9360
9361                 let events = nodes[0].node.get_and_clear_pending_events();
9362                 match events[0] {
9363                         Event::PaymentSent { ref payment_preimage } => {
9364                                 assert_eq!(*payment_preimage, our_payment_preimage);
9365                         }
9366                         _ => panic!("Unexpected event"),
9367                 }
9368         }
9369
9370         #[test]
9371         fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
9372                 let nodes = create_network(2);
9373
9374                 // Create some initial channels
9375                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9376
9377                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
9378                 let local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9379                 assert_eq!(local_txn[0].input.len(), 1);
9380                 check_spends!(local_txn[0], chan_1.3.clone());
9381
9382                 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
9383                 nodes[1].node.claim_funds(payment_preimage);
9384                 check_added_monitors!(nodes[1], 1);
9385                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9386                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
9387                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9388                 match events[0] {
9389                         MessageSendEvent::UpdateHTLCs { .. } => {},
9390                         _ => panic!("Unexpected event"),
9391                 }
9392                 match events[1] {
9393                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9394                         _ => panic!("Unexepected event"),
9395                 }
9396                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9397                 assert_eq!(node_txn[0].input.len(), 1);
9398                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9399                 check_spends!(node_txn[0], local_txn[0].clone());
9400
9401                 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
9402                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9403                 assert_eq!(spend_txn.len(), 2);
9404                 check_spends!(spend_txn[0], node_txn[0].clone());
9405                 check_spends!(spend_txn[1], node_txn[2].clone());
9406         }
9407
9408         #[test]
9409         fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
9410                 let nodes = create_network(2);
9411
9412                 // Create some initial channels
9413                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9414
9415                 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
9416                 let local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9417                 assert_eq!(local_txn[0].input.len(), 1);
9418                 check_spends!(local_txn[0], chan_1.3.clone());
9419
9420                 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
9421                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9422                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
9423                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9424                 match events[0] {
9425                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9426                         _ => panic!("Unexepected event"),
9427                 }
9428                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9429                 assert_eq!(node_txn[0].input.len(), 1);
9430                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9431                 check_spends!(node_txn[0], local_txn[0].clone());
9432
9433                 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
9434                 let spend_txn = check_spendable_outputs!(nodes[0], 1);
9435                 assert_eq!(spend_txn.len(), 8);
9436                 assert_eq!(spend_txn[0], spend_txn[2]);
9437                 assert_eq!(spend_txn[0], spend_txn[4]);
9438                 assert_eq!(spend_txn[0], spend_txn[6]);
9439                 assert_eq!(spend_txn[1], spend_txn[3]);
9440                 assert_eq!(spend_txn[1], spend_txn[5]);
9441                 assert_eq!(spend_txn[1], spend_txn[7]);
9442                 check_spends!(spend_txn[0], local_txn[0].clone());
9443                 check_spends!(spend_txn[1], node_txn[0].clone());
9444         }
9445
9446         #[test]
9447         fn test_static_output_closing_tx() {
9448                 let nodes = create_network(2);
9449
9450                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
9451
9452                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
9453                 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
9454
9455                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9456                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
9457                 let spend_txn = check_spendable_outputs!(nodes[0], 2);
9458                 assert_eq!(spend_txn.len(), 1);
9459                 check_spends!(spend_txn[0], closing_tx.clone());
9460
9461                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
9462                 let spend_txn = check_spendable_outputs!(nodes[1], 2);
9463                 assert_eq!(spend_txn.len(), 1);
9464                 check_spends!(spend_txn[0], closing_tx);
9465         }
9466 }