Add test_util for overriding session privs for onion crypt
[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                 keys_manager: Arc<test_utils::TestKeysInterface>,
3574                 node: Arc<ChannelManager>,
3575                 router: Router,
3576                 node_seed: [u8; 32],
3577                 network_payment_count: Rc<RefCell<u8>>,
3578                 network_chan_count: Rc<RefCell<u32>>,
3579         }
3580         impl Drop for Node {
3581                 fn drop(&mut self) {
3582                         if !::std::thread::panicking() {
3583                                 // Check that we processed all pending events
3584                                 assert_eq!(self.node.get_and_clear_pending_msg_events().len(), 0);
3585                                 assert_eq!(self.node.get_and_clear_pending_events().len(), 0);
3586                                 assert_eq!(self.chan_monitor.added_monitors.lock().unwrap().len(), 0);
3587                         }
3588                 }
3589         }
3590
3591         fn create_chan_between_nodes(node_a: &Node, node_b: &Node) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3592                 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001)
3593         }
3594
3595         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) {
3596                 let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat);
3597                 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
3598                 (announcement, as_update, bs_update, channel_id, tx)
3599         }
3600
3601         macro_rules! get_revoke_commit_msgs {
3602                 ($node: expr, $node_id: expr) => {
3603                         {
3604                                 let events = $node.node.get_and_clear_pending_msg_events();
3605                                 assert_eq!(events.len(), 2);
3606                                 (match events[0] {
3607                                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3608                                                 assert_eq!(*node_id, $node_id);
3609                                                 (*msg).clone()
3610                                         },
3611                                         _ => panic!("Unexpected event"),
3612                                 }, match events[1] {
3613                                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3614                                                 assert_eq!(*node_id, $node_id);
3615                                                 assert!(updates.update_add_htlcs.is_empty());
3616                                                 assert!(updates.update_fulfill_htlcs.is_empty());
3617                                                 assert!(updates.update_fail_htlcs.is_empty());
3618                                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
3619                                                 assert!(updates.update_fee.is_none());
3620                                                 updates.commitment_signed.clone()
3621                                         },
3622                                         _ => panic!("Unexpected event"),
3623                                 })
3624                         }
3625                 }
3626         }
3627
3628         macro_rules! get_event_msg {
3629                 ($node: expr, $event_type: path, $node_id: expr) => {
3630                         {
3631                                 let events = $node.node.get_and_clear_pending_msg_events();
3632                                 assert_eq!(events.len(), 1);
3633                                 match events[0] {
3634                                         $event_type { ref node_id, ref msg } => {
3635                                                 assert_eq!(*node_id, $node_id);
3636                                                 (*msg).clone()
3637                                         },
3638                                         _ => panic!("Unexpected event"),
3639                                 }
3640                         }
3641                 }
3642         }
3643
3644         macro_rules! get_htlc_update_msgs {
3645                 ($node: expr, $node_id: expr) => {
3646                         {
3647                                 let events = $node.node.get_and_clear_pending_msg_events();
3648                                 assert_eq!(events.len(), 1);
3649                                 match events[0] {
3650                                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3651                                                 assert_eq!(*node_id, $node_id);
3652                                                 (*updates).clone()
3653                                         },
3654                                         _ => panic!("Unexpected event"),
3655                                 }
3656                         }
3657                 }
3658         }
3659
3660         macro_rules! get_feerate {
3661                 ($node: expr, $channel_id: expr) => {
3662                         {
3663                                 let chan_lock = $node.node.channel_state.lock().unwrap();
3664                                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
3665                                 chan.get_feerate()
3666                         }
3667                 }
3668         }
3669
3670
3671         fn create_chan_between_nodes_with_value_init(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> Transaction {
3672                 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
3673                 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();
3674                 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();
3675
3676                 let chan_id = *node_a.network_chan_count.borrow();
3677                 let tx;
3678                 let funding_output;
3679
3680                 let events_2 = node_a.node.get_and_clear_pending_events();
3681                 assert_eq!(events_2.len(), 1);
3682                 match events_2[0] {
3683                         Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
3684                                 assert_eq!(*channel_value_satoshis, channel_value);
3685                                 assert_eq!(user_channel_id, 42);
3686
3687                                 tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
3688                                         value: *channel_value_satoshis, script_pubkey: output_script.clone(),
3689                                 }]};
3690                                 funding_output = OutPoint::new(tx.txid(), 0);
3691
3692                                 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
3693                                 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3694                                 assert_eq!(added_monitors.len(), 1);
3695                                 assert_eq!(added_monitors[0].0, funding_output);
3696                                 added_monitors.clear();
3697                         },
3698                         _ => panic!("Unexpected event"),
3699                 }
3700
3701                 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();
3702                 {
3703                         let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
3704                         assert_eq!(added_monitors.len(), 1);
3705                         assert_eq!(added_monitors[0].0, funding_output);
3706                         added_monitors.clear();
3707                 }
3708
3709                 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();
3710                 {
3711                         let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3712                         assert_eq!(added_monitors.len(), 1);
3713                         assert_eq!(added_monitors[0].0, funding_output);
3714                         added_monitors.clear();
3715                 }
3716
3717                 let events_4 = node_a.node.get_and_clear_pending_events();
3718                 assert_eq!(events_4.len(), 1);
3719                 match events_4[0] {
3720                         Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
3721                                 assert_eq!(user_channel_id, 42);
3722                                 assert_eq!(*funding_txo, funding_output);
3723                         },
3724                         _ => panic!("Unexpected event"),
3725                 };
3726
3727                 tx
3728         }
3729
3730         fn create_chan_between_nodes_with_value_confirm(node_a: &Node, node_b: &Node, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
3731                 confirm_transaction(&node_b.chain_monitor, &tx, tx.version);
3732                 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();
3733
3734                 let channel_id;
3735
3736                 confirm_transaction(&node_a.chain_monitor, &tx, tx.version);
3737                 let events_6 = node_a.node.get_and_clear_pending_msg_events();
3738                 assert_eq!(events_6.len(), 2);
3739                 ((match events_6[0] {
3740                         MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3741                                 channel_id = msg.channel_id.clone();
3742                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
3743                                 msg.clone()
3744                         },
3745                         _ => panic!("Unexpected event"),
3746                 }, match events_6[1] {
3747                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3748                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
3749                                 msg.clone()
3750                         },
3751                         _ => panic!("Unexpected event"),
3752                 }), channel_id)
3753         }
3754
3755         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) {
3756                 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat);
3757                 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
3758                 (msgs, chan_id, tx)
3759         }
3760
3761         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) {
3762                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0).unwrap();
3763                 let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
3764                 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1).unwrap();
3765
3766                 let events_7 = node_b.node.get_and_clear_pending_msg_events();
3767                 assert_eq!(events_7.len(), 1);
3768                 let (announcement, bs_update) = match events_7[0] {
3769                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3770                                 (msg, update_msg)
3771                         },
3772                         _ => panic!("Unexpected event"),
3773                 };
3774
3775                 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs).unwrap();
3776                 let events_8 = node_a.node.get_and_clear_pending_msg_events();
3777                 assert_eq!(events_8.len(), 1);
3778                 let as_update = match events_8[0] {
3779                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3780                                 assert!(*announcement == *msg);
3781                                 assert_eq!(update_msg.contents.short_channel_id, announcement.contents.short_channel_id);
3782                                 assert_eq!(update_msg.contents.short_channel_id, bs_update.contents.short_channel_id);
3783                                 update_msg
3784                         },
3785                         _ => panic!("Unexpected event"),
3786                 };
3787
3788                 *node_a.network_chan_count.borrow_mut() += 1;
3789
3790                 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
3791         }
3792
3793         fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3794                 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001)
3795         }
3796
3797         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) {
3798                 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat);
3799                 for node in nodes {
3800                         assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
3801                         node.router.handle_channel_update(&chan_announcement.1).unwrap();
3802                         node.router.handle_channel_update(&chan_announcement.2).unwrap();
3803                 }
3804                 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
3805         }
3806
3807         macro_rules! check_spends {
3808                 ($tx: expr, $spends_tx: expr) => {
3809                         {
3810                                 let mut funding_tx_map = HashMap::new();
3811                                 let spends_tx = $spends_tx;
3812                                 funding_tx_map.insert(spends_tx.txid(), spends_tx);
3813                                 $tx.verify(&funding_tx_map).unwrap();
3814                         }
3815                 }
3816         }
3817
3818         macro_rules! get_closing_signed_broadcast {
3819                 ($node: expr, $dest_pubkey: expr) => {
3820                         {
3821                                 let events = $node.get_and_clear_pending_msg_events();
3822                                 assert!(events.len() == 1 || events.len() == 2);
3823                                 (match events[events.len() - 1] {
3824                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
3825                                                 assert_eq!(msg.contents.flags & 2, 2);
3826                                                 msg.clone()
3827                                         },
3828                                         _ => panic!("Unexpected event"),
3829                                 }, if events.len() == 2 {
3830                                         match events[0] {
3831                                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3832                                                         assert_eq!(*node_id, $dest_pubkey);
3833                                                         Some(msg.clone())
3834                                                 },
3835                                                 _ => panic!("Unexpected event"),
3836                                         }
3837                                 } else { None })
3838                         }
3839                 }
3840         }
3841
3842         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) {
3843                 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) };
3844                 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
3845                 let (tx_a, tx_b);
3846
3847                 node_a.close_channel(channel_id).unwrap();
3848                 node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id())).unwrap();
3849
3850                 let events_1 = node_b.get_and_clear_pending_msg_events();
3851                 assert!(events_1.len() >= 1);
3852                 let shutdown_b = match events_1[0] {
3853                         MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
3854                                 assert_eq!(node_id, &node_a.get_our_node_id());
3855                                 msg.clone()
3856                         },
3857                         _ => panic!("Unexpected event"),
3858                 };
3859
3860                 let closing_signed_b = if !close_inbound_first {
3861                         assert_eq!(events_1.len(), 1);
3862                         None
3863                 } else {
3864                         Some(match events_1[1] {
3865                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3866                                         assert_eq!(node_id, &node_a.get_our_node_id());
3867                                         msg.clone()
3868                                 },
3869                                 _ => panic!("Unexpected event"),
3870                         })
3871                 };
3872
3873                 node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b).unwrap();
3874                 let (as_update, bs_update) = if close_inbound_first {
3875                         assert!(node_a.get_and_clear_pending_msg_events().is_empty());
3876                         node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3877                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3878                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3879                         let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3880
3881                         node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
3882                         let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3883                         assert!(none_b.is_none());
3884                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3885                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3886                         (as_update, bs_update)
3887                 } else {
3888                         let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
3889
3890                         node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a).unwrap();
3891                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3892                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3893                         let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3894
3895                         node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3896                         let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3897                         assert!(none_a.is_none());
3898                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3899                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3900                         (as_update, bs_update)
3901                 };
3902                 assert_eq!(tx_a, tx_b);
3903                 check_spends!(tx_a, funding_tx);
3904
3905                 (as_update, bs_update, tx_a)
3906         }
3907
3908         struct SendEvent {
3909                 node_id: PublicKey,
3910                 msgs: Vec<msgs::UpdateAddHTLC>,
3911                 commitment_msg: msgs::CommitmentSigned,
3912         }
3913         impl SendEvent {
3914                 fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
3915                         assert!(updates.update_fulfill_htlcs.is_empty());
3916                         assert!(updates.update_fail_htlcs.is_empty());
3917                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3918                         assert!(updates.update_fee.is_none());
3919                         SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
3920                 }
3921
3922                 fn from_event(event: MessageSendEvent) -> SendEvent {
3923                         match event {
3924                                 MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
3925                                 _ => panic!("Unexpected event type!"),
3926                         }
3927                 }
3928
3929                 fn from_node(node: &Node) -> SendEvent {
3930                         let mut events = node.node.get_and_clear_pending_msg_events();
3931                         assert_eq!(events.len(), 1);
3932                         SendEvent::from_event(events.pop().unwrap())
3933                 }
3934         }
3935
3936         macro_rules! check_added_monitors {
3937                 ($node: expr, $count: expr) => {
3938                         {
3939                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
3940                                 assert_eq!(added_monitors.len(), $count);
3941                                 added_monitors.clear();
3942                         }
3943                 }
3944         }
3945
3946         macro_rules! commitment_signed_dance {
3947                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
3948                         {
3949                                 check_added_monitors!($node_a, 0);
3950                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3951                                 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3952                                 check_added_monitors!($node_a, 1);
3953                                 commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
3954                         }
3955                 };
3956                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
3957                         {
3958                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
3959                                 check_added_monitors!($node_b, 0);
3960                                 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3961                                 $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
3962                                 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3963                                 check_added_monitors!($node_b, 1);
3964                                 $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed).unwrap();
3965                                 let (bs_revoke_and_ack, extra_msg_option) = {
3966                                         let events = $node_b.node.get_and_clear_pending_msg_events();
3967                                         assert!(events.len() <= 2);
3968                                         (match events[0] {
3969                                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3970                                                         assert_eq!(*node_id, $node_a.node.get_our_node_id());
3971                                                         (*msg).clone()
3972                                                 },
3973                                                 _ => panic!("Unexpected event"),
3974                                         }, events.get(1).map(|e| e.clone()))
3975                                 };
3976                                 check_added_monitors!($node_b, 1);
3977                                 if $fail_backwards {
3978                                         assert!($node_a.node.get_and_clear_pending_events().is_empty());
3979                                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3980                                 }
3981                                 (extra_msg_option, bs_revoke_and_ack)
3982                         }
3983                 };
3984                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
3985                         {
3986                                 check_added_monitors!($node_a, 0);
3987                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3988                                 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3989                                 check_added_monitors!($node_a, 1);
3990                                 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
3991                                 assert!(extra_msg_option.is_none());
3992                                 bs_revoke_and_ack
3993                         }
3994                 };
3995                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
3996                         {
3997                                 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
3998                                 $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
3999                                 {
4000                                         let mut added_monitors = $node_a.chan_monitor.added_monitors.lock().unwrap();
4001                                         if $fail_backwards {
4002                                                 assert_eq!(added_monitors.len(), 2);
4003                                                 assert!(added_monitors[0].0 != added_monitors[1].0);
4004                                         } else {
4005                                                 assert_eq!(added_monitors.len(), 1);
4006                                         }
4007                                         added_monitors.clear();
4008                                 }
4009                                 extra_msg_option
4010                         }
4011                 };
4012                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
4013                         {
4014                                 assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
4015                         }
4016                 };
4017                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
4018                         {
4019                                 commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
4020                                 if $fail_backwards {
4021                                         let channel_state = $node_a.node.channel_state.lock().unwrap();
4022                                         assert_eq!(channel_state.pending_msg_events.len(), 1);
4023                                         if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
4024                                                 assert_ne!(*node_id, $node_b.node.get_our_node_id());
4025                                         } else { panic!("Unexpected event"); }
4026                                 } else {
4027                                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
4028                                 }
4029                         }
4030                 }
4031         }
4032
4033         macro_rules! get_payment_preimage_hash {
4034                 ($node: expr) => {
4035                         {
4036                                 let payment_preimage = PaymentPreimage([*$node.network_payment_count.borrow(); 32]);
4037                                 *$node.network_payment_count.borrow_mut() += 1;
4038                                 let mut payment_hash = PaymentHash([0; 32]);
4039                                 let mut sha = Sha256::new();
4040                                 sha.input(&payment_preimage.0[..]);
4041                                 sha.result(&mut payment_hash.0[..]);
4042                                 (payment_preimage, payment_hash)
4043                         }
4044                 }
4045         }
4046
4047         fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
4048                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4049
4050                 let mut payment_event = {
4051                         origin_node.node.send_payment(route, our_payment_hash).unwrap();
4052                         check_added_monitors!(origin_node, 1);
4053
4054                         let mut events = origin_node.node.get_and_clear_pending_msg_events();
4055                         assert_eq!(events.len(), 1);
4056                         SendEvent::from_event(events.remove(0))
4057                 };
4058                 let mut prev_node = origin_node;
4059
4060                 for (idx, &node) in expected_route.iter().enumerate() {
4061                         assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
4062
4063                         node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4064                         check_added_monitors!(node, 0);
4065                         commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
4066
4067                         let events_1 = node.node.get_and_clear_pending_events();
4068                         assert_eq!(events_1.len(), 1);
4069                         match events_1[0] {
4070                                 Event::PendingHTLCsForwardable { .. } => { },
4071                                 _ => panic!("Unexpected event"),
4072                         };
4073
4074                         node.node.channel_state.lock().unwrap().next_forward = Instant::now();
4075                         node.node.process_pending_htlc_forwards();
4076
4077                         if idx == expected_route.len() - 1 {
4078                                 let events_2 = node.node.get_and_clear_pending_events();
4079                                 assert_eq!(events_2.len(), 1);
4080                                 match events_2[0] {
4081                                         Event::PaymentReceived { ref payment_hash, amt } => {
4082                                                 assert_eq!(our_payment_hash, *payment_hash);
4083                                                 assert_eq!(amt, recv_value);
4084                                         },
4085                                         _ => panic!("Unexpected event"),
4086                                 }
4087                         } else {
4088                                 let mut events_2 = node.node.get_and_clear_pending_msg_events();
4089                                 assert_eq!(events_2.len(), 1);
4090                                 check_added_monitors!(node, 1);
4091                                 payment_event = SendEvent::from_event(events_2.remove(0));
4092                                 assert_eq!(payment_event.msgs.len(), 1);
4093                         }
4094
4095                         prev_node = node;
4096                 }
4097
4098                 (our_payment_preimage, our_payment_hash)
4099         }
4100
4101         fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: PaymentPreimage) {
4102                 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
4103                 check_added_monitors!(expected_route.last().unwrap(), 1);
4104
4105                 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
4106                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4107                 macro_rules! get_next_msgs {
4108                         ($node: expr) => {
4109                                 {
4110                                         let events = $node.node.get_and_clear_pending_msg_events();
4111                                         assert_eq!(events.len(), 1);
4112                                         match events[0] {
4113                                                 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 } } => {
4114                                                         assert!(update_add_htlcs.is_empty());
4115                                                         assert_eq!(update_fulfill_htlcs.len(), 1);
4116                                                         assert!(update_fail_htlcs.is_empty());
4117                                                         assert!(update_fail_malformed_htlcs.is_empty());
4118                                                         assert!(update_fee.is_none());
4119                                                         expected_next_node = node_id.clone();
4120                                                         Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()))
4121                                                 },
4122                                                 _ => panic!("Unexpected event"),
4123                                         }
4124                                 }
4125                         }
4126                 }
4127
4128                 macro_rules! last_update_fulfill_dance {
4129                         ($node: expr, $prev_node: expr) => {
4130                                 {
4131                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4132                                         check_added_monitors!($node, 0);
4133                                         assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4134                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4135                                 }
4136                         }
4137                 }
4138                 macro_rules! mid_update_fulfill_dance {
4139                         ($node: expr, $prev_node: expr, $new_msgs: expr) => {
4140                                 {
4141                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4142                                         check_added_monitors!($node, 1);
4143                                         let new_next_msgs = if $new_msgs {
4144                                                 get_next_msgs!($node)
4145                                         } else {
4146                                                 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4147                                                 None
4148                                         };
4149                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4150                                         next_msgs = new_next_msgs;
4151                                 }
4152                         }
4153                 }
4154
4155                 let mut prev_node = expected_route.last().unwrap();
4156                 for (idx, node) in expected_route.iter().rev().enumerate() {
4157                         assert_eq!(expected_next_node, node.node.get_our_node_id());
4158                         let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
4159                         if next_msgs.is_some() {
4160                                 mid_update_fulfill_dance!(node, prev_node, update_next_msgs);
4161                         } else if update_next_msgs {
4162                                 next_msgs = get_next_msgs!(node);
4163                         } else {
4164                                 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
4165                         }
4166                         if !skip_last && idx == expected_route.len() - 1 {
4167                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4168                         }
4169
4170                         prev_node = node;
4171                 }
4172
4173                 if !skip_last {
4174                         last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
4175                         let events = origin_node.node.get_and_clear_pending_events();
4176                         assert_eq!(events.len(), 1);
4177                         match events[0] {
4178                                 Event::PaymentSent { payment_preimage } => {
4179                                         assert_eq!(payment_preimage, our_payment_preimage);
4180                                 },
4181                                 _ => panic!("Unexpected event"),
4182                         }
4183                 }
4184         }
4185
4186         fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: PaymentPreimage) {
4187                 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage);
4188         }
4189
4190         const TEST_FINAL_CLTV: u32 = 32;
4191
4192         fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
4193                 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();
4194                 assert_eq!(route.hops.len(), expected_route.len());
4195                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4196                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
4197                 }
4198
4199                 send_along_route(origin_node, route, expected_route, recv_value)
4200         }
4201
4202         fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
4203                 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();
4204                 assert_eq!(route.hops.len(), expected_route.len());
4205                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4206                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
4207                 }
4208
4209                 let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4210
4211                 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
4212                 match err {
4213                         APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
4214                         _ => panic!("Unknown error variants"),
4215                 };
4216         }
4217
4218         fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
4219                 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
4220                 claim_payment(&origin, expected_route, our_payment_preimage);
4221         }
4222
4223         fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: PaymentHash) {
4224                 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash, PaymentFailReason::PreimageUnknown));
4225                 check_added_monitors!(expected_route.last().unwrap(), 1);
4226
4227                 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
4228                 macro_rules! update_fail_dance {
4229                         ($node: expr, $prev_node: expr, $last_node: expr) => {
4230                                 {
4231                                         $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4232                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
4233                                 }
4234                         }
4235                 }
4236
4237                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4238                 let mut prev_node = expected_route.last().unwrap();
4239                 for (idx, node) in expected_route.iter().rev().enumerate() {
4240                         assert_eq!(expected_next_node, node.node.get_our_node_id());
4241                         if next_msgs.is_some() {
4242                                 // We may be the "last node" for the purpose of the commitment dance if we're
4243                                 // skipping the last node (implying it is disconnected) and we're the
4244                                 // second-to-last node!
4245                                 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
4246                         }
4247
4248                         let events = node.node.get_and_clear_pending_msg_events();
4249                         if !skip_last || idx != expected_route.len() - 1 {
4250                                 assert_eq!(events.len(), 1);
4251                                 match events[0] {
4252                                         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 } } => {
4253                                                 assert!(update_add_htlcs.is_empty());
4254                                                 assert!(update_fulfill_htlcs.is_empty());
4255                                                 assert_eq!(update_fail_htlcs.len(), 1);
4256                                                 assert!(update_fail_malformed_htlcs.is_empty());
4257                                                 assert!(update_fee.is_none());
4258                                                 expected_next_node = node_id.clone();
4259                                                 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
4260                                         },
4261                                         _ => panic!("Unexpected event"),
4262                                 }
4263                         } else {
4264                                 assert!(events.is_empty());
4265                         }
4266                         if !skip_last && idx == expected_route.len() - 1 {
4267                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4268                         }
4269
4270                         prev_node = node;
4271                 }
4272
4273                 if !skip_last {
4274                         update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
4275
4276                         let events = origin_node.node.get_and_clear_pending_events();
4277                         assert_eq!(events.len(), 1);
4278                         match events[0] {
4279                                 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
4280                                         assert_eq!(payment_hash, our_payment_hash);
4281                                         assert!(rejected_by_dest);
4282                                 },
4283                                 _ => panic!("Unexpected event"),
4284                         }
4285                 }
4286         }
4287
4288         fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: PaymentHash) {
4289                 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
4290         }
4291
4292         fn create_network(node_count: usize) -> Vec<Node> {
4293                 let mut nodes = Vec::new();
4294                 let mut rng = thread_rng();
4295                 let secp_ctx = Secp256k1::new();
4296
4297                 let chan_count = Rc::new(RefCell::new(0));
4298                 let payment_count = Rc::new(RefCell::new(0));
4299
4300                 for i in 0..node_count {
4301                         let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
4302                         let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
4303                         let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
4304                         let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
4305                         let mut seed = [0; 32];
4306                         rng.fill_bytes(&mut seed);
4307                         let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&seed, Network::Testnet, Arc::clone(&logger)));
4308                         let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone()));
4309                         let mut config = UserConfig::new();
4310                         config.channel_options.announced_channel = true;
4311                         config.channel_limits.force_announced_channel_preference = false;
4312                         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();
4313                         let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), chain_monitor.clone(), Arc::clone(&logger));
4314                         nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router, keys_manager, node_seed: seed,
4315                                 network_payment_count: payment_count.clone(),
4316                                 network_chan_count: chan_count.clone(),
4317                         });
4318                 }
4319
4320                 nodes
4321         }
4322
4323         #[test]
4324         fn test_async_inbound_update_fee() {
4325                 let mut nodes = create_network(2);
4326                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4327                 let channel_id = chan.2;
4328
4329                 // balancing
4330                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4331
4332                 // A                                        B
4333                 // update_fee                            ->
4334                 // send (1) commitment_signed            -.
4335                 //                                       <- update_add_htlc/commitment_signed
4336                 // send (2) RAA (awaiting remote revoke) -.
4337                 // (1) commitment_signed is delivered    ->
4338                 //                                       .- send (3) RAA (awaiting remote revoke)
4339                 // (2) RAA is delivered                  ->
4340                 //                                       .- send (4) commitment_signed
4341                 //                                       <- (3) RAA is delivered
4342                 // send (5) commitment_signed            -.
4343                 //                                       <- (4) commitment_signed is delivered
4344                 // send (6) RAA                          -.
4345                 // (5) commitment_signed is delivered    ->
4346                 //                                       <- RAA
4347                 // (6) RAA is delivered                  ->
4348
4349                 // First nodes[0] generates an update_fee
4350                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4351                 check_added_monitors!(nodes[0], 1);
4352
4353                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4354                 assert_eq!(events_0.len(), 1);
4355                 let (update_msg, commitment_signed) = match events_0[0] { // (1)
4356                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4357                                 (update_fee.as_ref(), commitment_signed)
4358                         },
4359                         _ => panic!("Unexpected event"),
4360                 };
4361
4362                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4363
4364                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4365                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4366                 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();
4367                 check_added_monitors!(nodes[1], 1);
4368
4369                 let payment_event = {
4370                         let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4371                         assert_eq!(events_1.len(), 1);
4372                         SendEvent::from_event(events_1.remove(0))
4373                 };
4374                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4375                 assert_eq!(payment_event.msgs.len(), 1);
4376
4377                 // ...now when the messages get delivered everyone should be happy
4378                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4379                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4380                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4381                 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4382                 check_added_monitors!(nodes[0], 1);
4383
4384                 // deliver(1), generate (3):
4385                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4386                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4387                 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
4388                 check_added_monitors!(nodes[1], 1);
4389
4390                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap(); // deliver (2)
4391                 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4392                 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
4393                 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
4394                 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
4395                 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
4396                 assert!(bs_update.update_fee.is_none()); // (4)
4397                 check_added_monitors!(nodes[1], 1);
4398
4399                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap(); // deliver (3)
4400                 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4401                 assert!(as_update.update_add_htlcs.is_empty()); // (5)
4402                 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
4403                 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
4404                 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
4405                 assert!(as_update.update_fee.is_none()); // (5)
4406                 check_added_monitors!(nodes[0], 1);
4407
4408                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed).unwrap(); // deliver (4)
4409                 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4410                 // only (6) so get_event_msg's assert(len == 1) passes
4411                 check_added_monitors!(nodes[0], 1);
4412
4413                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed).unwrap(); // deliver (5)
4414                 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4415                 check_added_monitors!(nodes[1], 1);
4416
4417                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4418                 check_added_monitors!(nodes[0], 1);
4419
4420                 let events_2 = nodes[0].node.get_and_clear_pending_events();
4421                 assert_eq!(events_2.len(), 1);
4422                 match events_2[0] {
4423                         Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
4424                         _ => panic!("Unexpected event"),
4425                 }
4426
4427                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap(); // deliver (6)
4428                 check_added_monitors!(nodes[1], 1);
4429         }
4430
4431         #[test]
4432         fn test_update_fee_unordered_raa() {
4433                 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
4434                 // crash in an earlier version of the update_fee patch)
4435                 let mut nodes = create_network(2);
4436                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4437                 let channel_id = chan.2;
4438
4439                 // balancing
4440                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4441
4442                 // First nodes[0] generates an update_fee
4443                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4444                 check_added_monitors!(nodes[0], 1);
4445
4446                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4447                 assert_eq!(events_0.len(), 1);
4448                 let update_msg = match events_0[0] { // (1)
4449                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
4450                                 update_fee.as_ref()
4451                         },
4452                         _ => panic!("Unexpected event"),
4453                 };
4454
4455                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4456
4457                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4458                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4459                 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();
4460                 check_added_monitors!(nodes[1], 1);
4461
4462                 let payment_event = {
4463                         let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4464                         assert_eq!(events_1.len(), 1);
4465                         SendEvent::from_event(events_1.remove(0))
4466                 };
4467                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4468                 assert_eq!(payment_event.msgs.len(), 1);
4469
4470                 // ...now when the messages get delivered everyone should be happy
4471                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4472                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4473                 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4474                 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4475                 check_added_monitors!(nodes[0], 1);
4476
4477                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap(); // deliver (2)
4478                 check_added_monitors!(nodes[1], 1);
4479
4480                 // We can't continue, sadly, because our (1) now has a bogus signature
4481         }
4482
4483         #[test]
4484         fn test_multi_flight_update_fee() {
4485                 let nodes = create_network(2);
4486                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4487                 let channel_id = chan.2;
4488
4489                 // A                                        B
4490                 // update_fee/commitment_signed          ->
4491                 //                                       .- send (1) RAA and (2) commitment_signed
4492                 // update_fee (never committed)          ->
4493                 // (3) update_fee                        ->
4494                 // We have to manually generate the above update_fee, it is allowed by the protocol but we
4495                 // don't track which updates correspond to which revoke_and_ack responses so we're in
4496                 // AwaitingRAA mode and will not generate the update_fee yet.
4497                 //                                       <- (1) RAA delivered
4498                 // (3) is generated and send (4) CS      -.
4499                 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
4500                 // know the per_commitment_point to use for it.
4501                 //                                       <- (2) commitment_signed delivered
4502                 // revoke_and_ack                        ->
4503                 //                                          B should send no response here
4504                 // (4) commitment_signed delivered       ->
4505                 //                                       <- RAA/commitment_signed delivered
4506                 // revoke_and_ack                        ->
4507
4508                 // First nodes[0] generates an update_fee
4509                 let initial_feerate = get_feerate!(nodes[0], channel_id);
4510                 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
4511                 check_added_monitors!(nodes[0], 1);
4512
4513                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4514                 assert_eq!(events_0.len(), 1);
4515                 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
4516                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4517                                 (update_fee.as_ref().unwrap(), commitment_signed)
4518                         },
4519                         _ => panic!("Unexpected event"),
4520                 };
4521
4522                 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
4523                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1).unwrap();
4524                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1).unwrap();
4525                 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4526                 check_added_monitors!(nodes[1], 1);
4527
4528                 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
4529                 // transaction:
4530                 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
4531                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4532                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4533
4534                 // Create the (3) update_fee message that nodes[0] will generate before it does...
4535                 let mut update_msg_2 = msgs::UpdateFee {
4536                         channel_id: update_msg_1.channel_id.clone(),
4537                         feerate_per_kw: (initial_feerate + 30) as u32,
4538                 };
4539
4540                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4541
4542                 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
4543                 // Deliver (3)
4544                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4545
4546                 // Deliver (1), generating (3) and (4)
4547                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap();
4548                 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4549                 check_added_monitors!(nodes[0], 1);
4550                 assert!(as_second_update.update_add_htlcs.is_empty());
4551                 assert!(as_second_update.update_fulfill_htlcs.is_empty());
4552                 assert!(as_second_update.update_fail_htlcs.is_empty());
4553                 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
4554                 // Check that the update_fee newly generated matches what we delivered:
4555                 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
4556                 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
4557
4558                 // Deliver (2) commitment_signed
4559                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
4560                 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4561                 check_added_monitors!(nodes[0], 1);
4562                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4563
4564                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap();
4565                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4566                 check_added_monitors!(nodes[1], 1);
4567
4568                 // Delever (4)
4569                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed).unwrap();
4570                 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4571                 check_added_monitors!(nodes[1], 1);
4572
4573                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4574                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4575                 check_added_monitors!(nodes[0], 1);
4576
4577                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment).unwrap();
4578                 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4579                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4580                 check_added_monitors!(nodes[0], 1);
4581
4582                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap();
4583                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4584                 check_added_monitors!(nodes[1], 1);
4585         }
4586
4587         #[test]
4588         fn test_update_fee_vanilla() {
4589                 let nodes = create_network(2);
4590                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4591                 let channel_id = chan.2;
4592
4593                 let feerate = get_feerate!(nodes[0], channel_id);
4594                 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
4595                 check_added_monitors!(nodes[0], 1);
4596
4597                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4598                 assert_eq!(events_0.len(), 1);
4599                 let (update_msg, commitment_signed) = match events_0[0] {
4600                                 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 } } => {
4601                                 (update_fee.as_ref(), commitment_signed)
4602                         },
4603                         _ => panic!("Unexpected event"),
4604                 };
4605                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4606
4607                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4608                 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4609                 check_added_monitors!(nodes[1], 1);
4610
4611                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4612                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4613                 check_added_monitors!(nodes[0], 1);
4614
4615                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4616                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4617                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4618                 check_added_monitors!(nodes[0], 1);
4619
4620                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4621                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4622                 check_added_monitors!(nodes[1], 1);
4623         }
4624
4625         #[test]
4626         fn test_update_fee_that_funder_cannot_afford() {
4627                 let nodes = create_network(2);
4628                 let channel_value = 1888;
4629                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000);
4630                 let channel_id = chan.2;
4631
4632                 let feerate = 260;
4633                 nodes[0].node.update_fee(channel_id, feerate).unwrap();
4634                 check_added_monitors!(nodes[0], 1);
4635                 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4636
4637                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap()).unwrap();
4638
4639                 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
4640
4641                 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
4642                 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
4643                 {
4644                         let chan_lock = nodes[1].node.channel_state.lock().unwrap();
4645                         let chan = chan_lock.by_id.get(&channel_id).unwrap();
4646
4647                         //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
4648                         let num_htlcs = chan.last_local_commitment_txn[0].output.len() - 2;
4649                         let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
4650                         let mut actual_fee = chan.last_local_commitment_txn[0].output.iter().fold(0, |acc, output| acc + output.value);
4651                         actual_fee = channel_value - actual_fee;
4652                         assert_eq!(total_fee, actual_fee);
4653                 } //drop the mutex
4654
4655                 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
4656                 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
4657                 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
4658                 check_added_monitors!(nodes[0], 1);
4659
4660                 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4661
4662                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap()).unwrap();
4663
4664                 //While producing the commitment_signed response after handling a received update_fee request the
4665                 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
4666                 //Should produce and error.
4667                 let err = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed).unwrap_err();
4668
4669                 assert!(match err.err {
4670                         "Funding remote cannot afford proposed new fee" => true,
4671                         _ => false,
4672                 });
4673
4674                 //clear the message we could not handle
4675                 nodes[1].node.get_and_clear_pending_msg_events();
4676         }
4677
4678         #[test]
4679         fn test_update_fee_with_fundee_update_add_htlc() {
4680                 let mut nodes = create_network(2);
4681                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4682                 let channel_id = chan.2;
4683
4684                 // balancing
4685                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4686
4687                 let feerate = get_feerate!(nodes[0], channel_id);
4688                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4689                 check_added_monitors!(nodes[0], 1);
4690
4691                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4692                 assert_eq!(events_0.len(), 1);
4693                 let (update_msg, commitment_signed) = match events_0[0] {
4694                                 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 } } => {
4695                                 (update_fee.as_ref(), commitment_signed)
4696                         },
4697                         _ => panic!("Unexpected event"),
4698                 };
4699                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4700                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4701                 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4702                 check_added_monitors!(nodes[1], 1);
4703
4704                 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
4705
4706                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
4707
4708                 // nothing happens since node[1] is in AwaitingRemoteRevoke
4709                 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
4710                 {
4711                         let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
4712                         assert_eq!(added_monitors.len(), 0);
4713                         added_monitors.clear();
4714                 }
4715                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4716                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4717                 // node[1] has nothing to do
4718
4719                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4720                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4721                 check_added_monitors!(nodes[0], 1);
4722
4723                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4724                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4725                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4726                 check_added_monitors!(nodes[0], 1);
4727                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4728                 check_added_monitors!(nodes[1], 1);
4729                 // AwaitingRemoteRevoke ends here
4730
4731                 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4732                 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
4733                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
4734                 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
4735                 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
4736                 assert_eq!(commitment_update.update_fee.is_none(), true);
4737
4738                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]).unwrap();
4739                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4740                 check_added_monitors!(nodes[0], 1);
4741                 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4742
4743                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke).unwrap();
4744                 check_added_monitors!(nodes[1], 1);
4745                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4746
4747                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed).unwrap();
4748                 check_added_monitors!(nodes[1], 1);
4749                 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4750                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4751
4752                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke).unwrap();
4753                 check_added_monitors!(nodes[0], 1);
4754                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4755
4756                 let events = nodes[0].node.get_and_clear_pending_events();
4757                 assert_eq!(events.len(), 1);
4758                 match events[0] {
4759                         Event::PendingHTLCsForwardable { .. } => { },
4760                         _ => panic!("Unexpected event"),
4761                 };
4762                 nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
4763                 nodes[0].node.process_pending_htlc_forwards();
4764
4765                 let events = nodes[0].node.get_and_clear_pending_events();
4766                 assert_eq!(events.len(), 1);
4767                 match events[0] {
4768                         Event::PaymentReceived { .. } => { },
4769                         _ => panic!("Unexpected event"),
4770                 };
4771
4772                 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
4773
4774                 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
4775                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
4776                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4777         }
4778
4779         #[test]
4780         fn test_update_fee() {
4781                 let nodes = create_network(2);
4782                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4783                 let channel_id = chan.2;
4784
4785                 // A                                        B
4786                 // (1) update_fee/commitment_signed      ->
4787                 //                                       <- (2) revoke_and_ack
4788                 //                                       .- send (3) commitment_signed
4789                 // (4) update_fee/commitment_signed      ->
4790                 //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
4791                 //                                       <- (3) commitment_signed delivered
4792                 // send (6) revoke_and_ack               -.
4793                 //                                       <- (5) deliver revoke_and_ack
4794                 // (6) deliver revoke_and_ack            ->
4795                 //                                       .- send (7) commitment_signed in response to (4)
4796                 //                                       <- (7) deliver commitment_signed
4797                 // revoke_and_ack                        ->
4798
4799                 // Create and deliver (1)...
4800                 let feerate = get_feerate!(nodes[0], channel_id);
4801                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4802                 check_added_monitors!(nodes[0], 1);
4803
4804                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4805                 assert_eq!(events_0.len(), 1);
4806                 let (update_msg, commitment_signed) = match events_0[0] {
4807                                 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 } } => {
4808                                 (update_fee.as_ref(), commitment_signed)
4809                         },
4810                         _ => panic!("Unexpected event"),
4811                 };
4812                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4813
4814                 // Generate (2) and (3):
4815                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4816                 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4817                 check_added_monitors!(nodes[1], 1);
4818
4819                 // Deliver (2):
4820                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4821                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4822                 check_added_monitors!(nodes[0], 1);
4823
4824                 // Create and deliver (4)...
4825                 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
4826                 check_added_monitors!(nodes[0], 1);
4827                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4828                 assert_eq!(events_0.len(), 1);
4829                 let (update_msg, commitment_signed) = match events_0[0] {
4830                                 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 } } => {
4831                                 (update_fee.as_ref(), commitment_signed)
4832                         },
4833                         _ => panic!("Unexpected event"),
4834                 };
4835
4836                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4837                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4838                 check_added_monitors!(nodes[1], 1);
4839                 // ... creating (5)
4840                 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4841                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4842
4843                 // Handle (3), creating (6):
4844                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0).unwrap();
4845                 check_added_monitors!(nodes[0], 1);
4846                 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4847                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4848
4849                 // Deliver (5):
4850                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4851                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4852                 check_added_monitors!(nodes[0], 1);
4853
4854                 // Deliver (6), creating (7):
4855                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0).unwrap();
4856                 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4857                 assert!(commitment_update.update_add_htlcs.is_empty());
4858                 assert!(commitment_update.update_fulfill_htlcs.is_empty());
4859                 assert!(commitment_update.update_fail_htlcs.is_empty());
4860                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
4861                 assert!(commitment_update.update_fee.is_none());
4862                 check_added_monitors!(nodes[1], 1);
4863
4864                 // Deliver (7)
4865                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4866                 check_added_monitors!(nodes[0], 1);
4867                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4868                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4869
4870                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4871                 check_added_monitors!(nodes[1], 1);
4872                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4873
4874                 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
4875                 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
4876                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4877         }
4878
4879         #[test]
4880         fn pre_funding_lock_shutdown_test() {
4881                 // Test sending a shutdown prior to funding_locked after funding generation
4882                 let nodes = create_network(2);
4883                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0);
4884                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4885                 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4886                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4887
4888                 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
4889                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4890                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4891                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4892                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4893
4894                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4895                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4896                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4897                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4898                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4899                 assert!(node_0_none.is_none());
4900
4901                 assert!(nodes[0].node.list_channels().is_empty());
4902                 assert!(nodes[1].node.list_channels().is_empty());
4903         }
4904
4905         #[test]
4906         fn updates_shutdown_wait() {
4907                 // Test sending a shutdown with outstanding updates pending
4908                 let mut nodes = create_network(3);
4909                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4910                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4911                 let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4912                 let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4913
4914                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
4915
4916                 nodes[0].node.close_channel(&chan_1.2).unwrap();
4917                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4918                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4919                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4920                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4921
4922                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4923                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4924
4925                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4926                 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route_1, payment_hash) {}
4927                 else { panic!("New sends should fail!") };
4928                 if let Err(APIError::ChannelUnavailable {..}) = nodes[1].node.send_payment(route_2, payment_hash) {}
4929                 else { panic!("New sends should fail!") };
4930
4931                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
4932                 check_added_monitors!(nodes[2], 1);
4933                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4934                 assert!(updates.update_add_htlcs.is_empty());
4935                 assert!(updates.update_fail_htlcs.is_empty());
4936                 assert!(updates.update_fail_malformed_htlcs.is_empty());
4937                 assert!(updates.update_fee.is_none());
4938                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4939                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
4940                 check_added_monitors!(nodes[1], 1);
4941                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4942                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
4943
4944                 assert!(updates_2.update_add_htlcs.is_empty());
4945                 assert!(updates_2.update_fail_htlcs.is_empty());
4946                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
4947                 assert!(updates_2.update_fee.is_none());
4948                 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
4949                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
4950                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
4951
4952                 let events = nodes[0].node.get_and_clear_pending_events();
4953                 assert_eq!(events.len(), 1);
4954                 match events[0] {
4955                         Event::PaymentSent { ref payment_preimage } => {
4956                                 assert_eq!(our_payment_preimage, *payment_preimage);
4957                         },
4958                         _ => panic!("Unexpected event"),
4959                 }
4960
4961                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4962                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4963                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4964                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4965                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4966                 assert!(node_0_none.is_none());
4967
4968                 assert!(nodes[0].node.list_channels().is_empty());
4969
4970                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4971                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
4972                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
4973                 assert!(nodes[1].node.list_channels().is_empty());
4974                 assert!(nodes[2].node.list_channels().is_empty());
4975         }
4976
4977         #[test]
4978         fn htlc_fail_async_shutdown() {
4979                 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
4980                 let mut nodes = create_network(3);
4981                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4982                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4983
4984                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4985                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4986                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
4987                 check_added_monitors!(nodes[0], 1);
4988                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4989                 assert_eq!(updates.update_add_htlcs.len(), 1);
4990                 assert!(updates.update_fulfill_htlcs.is_empty());
4991                 assert!(updates.update_fail_htlcs.is_empty());
4992                 assert!(updates.update_fail_malformed_htlcs.is_empty());
4993                 assert!(updates.update_fee.is_none());
4994
4995                 nodes[1].node.close_channel(&chan_1.2).unwrap();
4996                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4997                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4998                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4999
5000                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5001                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
5002                 check_added_monitors!(nodes[1], 1);
5003                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
5004                 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
5005
5006                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5007                 assert!(updates_2.update_add_htlcs.is_empty());
5008                 assert!(updates_2.update_fulfill_htlcs.is_empty());
5009                 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
5010                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
5011                 assert!(updates_2.update_fee.is_none());
5012
5013                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]).unwrap();
5014                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
5015
5016                 let events = nodes[0].node.get_and_clear_pending_events();
5017                 assert_eq!(events.len(), 1);
5018                 match events[0] {
5019                         Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } => {
5020                                 assert_eq!(our_payment_hash, *payment_hash);
5021                                 assert!(!rejected_by_dest);
5022                         },
5023                         _ => panic!("Unexpected event"),
5024                 }
5025
5026                 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5027                 assert_eq!(msg_events.len(), 2);
5028                 let node_0_closing_signed = match msg_events[0] {
5029                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
5030                                 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5031                                 (*msg).clone()
5032                         },
5033                         _ => panic!("Unexpected event"),
5034                 };
5035                 match msg_events[1] {
5036                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
5037                                 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
5038                         },
5039                         _ => panic!("Unexpected event"),
5040                 }
5041
5042                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5043                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5044                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5045                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5046                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5047                 assert!(node_0_none.is_none());
5048
5049                 assert!(nodes[0].node.list_channels().is_empty());
5050
5051                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5052                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5053                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5054                 assert!(nodes[1].node.list_channels().is_empty());
5055                 assert!(nodes[2].node.list_channels().is_empty());
5056         }
5057
5058         fn do_test_shutdown_rebroadcast(recv_count: u8) {
5059                 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
5060                 // messages delivered prior to disconnect
5061                 let nodes = create_network(3);
5062                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5063                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5064
5065                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
5066
5067                 nodes[1].node.close_channel(&chan_1.2).unwrap();
5068                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5069                 if recv_count > 0 {
5070                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
5071                         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5072                         if recv_count > 1 {
5073                                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
5074                         }
5075                 }
5076
5077                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5078                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5079
5080                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5081                 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5082                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5083                 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5084
5085                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish).unwrap();
5086                 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5087                 assert!(node_1_shutdown == node_1_2nd_shutdown);
5088
5089                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish).unwrap();
5090                 let node_0_2nd_shutdown = if recv_count > 0 {
5091                         let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5092                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5093                         node_0_2nd_shutdown
5094                 } else {
5095                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5096                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5097                         get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
5098                 };
5099                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown).unwrap();
5100
5101                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5102                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5103
5104                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
5105                 check_added_monitors!(nodes[2], 1);
5106                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5107                 assert!(updates.update_add_htlcs.is_empty());
5108                 assert!(updates.update_fail_htlcs.is_empty());
5109                 assert!(updates.update_fail_malformed_htlcs.is_empty());
5110                 assert!(updates.update_fee.is_none());
5111                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5112                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
5113                 check_added_monitors!(nodes[1], 1);
5114                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5115                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
5116
5117                 assert!(updates_2.update_add_htlcs.is_empty());
5118                 assert!(updates_2.update_fail_htlcs.is_empty());
5119                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
5120                 assert!(updates_2.update_fee.is_none());
5121                 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
5122                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
5123                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
5124
5125                 let events = nodes[0].node.get_and_clear_pending_events();
5126                 assert_eq!(events.len(), 1);
5127                 match events[0] {
5128                         Event::PaymentSent { ref payment_preimage } => {
5129                                 assert_eq!(our_payment_preimage, *payment_preimage);
5130                         },
5131                         _ => panic!("Unexpected event"),
5132                 }
5133
5134                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5135                 if recv_count > 0 {
5136                         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5137                         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5138                         assert!(node_1_closing_signed.is_some());
5139                 }
5140
5141                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5142                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5143
5144                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5145                 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5146                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5147                 if recv_count == 0 {
5148                         // If all closing_signeds weren't delivered we can just resume where we left off...
5149                         let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5150
5151                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish).unwrap();
5152                         let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5153                         assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
5154
5155                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish).unwrap();
5156                         let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5157                         assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
5158
5159                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown).unwrap();
5160                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5161
5162                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown).unwrap();
5163                         let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5164                         assert!(node_0_closing_signed == node_0_2nd_closing_signed);
5165
5166                         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed).unwrap();
5167                         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5168                         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5169                         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5170                         assert!(node_0_none.is_none());
5171                 } else {
5172                         // If one node, however, received + responded with an identical closing_signed we end
5173                         // up erroring and node[0] will try to broadcast its own latest commitment transaction.
5174                         // There isn't really anything better we can do simply, but in the future we might
5175                         // explore storing a set of recently-closed channels that got disconnected during
5176                         // closing_signed and avoiding broadcasting local commitment txn for some timeout to
5177                         // give our counterparty enough time to (potentially) broadcast a cooperative closing
5178                         // transaction.
5179                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5180
5181                         if let Err(msgs::HandleError{action: Some(msgs::ErrorAction::SendErrorMessage{msg}), ..}) =
5182                                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish) {
5183                                 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
5184                                 let msgs::ErrorMessage {ref channel_id, ..} = msg;
5185                                 assert_eq!(*channel_id, chan_1.2);
5186                         } else { panic!("Needed SendErrorMessage close"); }
5187
5188                         // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
5189                         // checks it, but in this case nodes[0] didn't ever get a chance to receive a
5190                         // closing_signed so we do it ourselves
5191                         let events = nodes[0].node.get_and_clear_pending_msg_events();
5192                         assert_eq!(events.len(), 1);
5193                         match events[0] {
5194                                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5195                                         assert_eq!(msg.contents.flags & 2, 2);
5196                                 },
5197                                 _ => panic!("Unexpected event"),
5198                         }
5199                 }
5200
5201                 assert!(nodes[0].node.list_channels().is_empty());
5202
5203                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5204                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5205                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5206                 assert!(nodes[1].node.list_channels().is_empty());
5207                 assert!(nodes[2].node.list_channels().is_empty());
5208         }
5209
5210         #[test]
5211         fn test_shutdown_rebroadcast() {
5212                 do_test_shutdown_rebroadcast(0);
5213                 do_test_shutdown_rebroadcast(1);
5214                 do_test_shutdown_rebroadcast(2);
5215         }
5216
5217         #[test]
5218         fn fake_network_test() {
5219                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5220                 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
5221                 let nodes = create_network(4);
5222
5223                 // Create some initial channels
5224                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5225                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5226                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5227
5228                 // Rebalance the network a bit by relaying one payment through all the channels...
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                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5233
5234                 // Send some more payments
5235                 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
5236                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
5237                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
5238
5239                 // Test failure packets
5240                 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
5241                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
5242
5243                 // Add a new channel that skips 3
5244                 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
5245
5246                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
5247                 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
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                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5253
5254                 // Do some rebalance loop payments, simultaneously
5255                 let mut hops = Vec::with_capacity(3);
5256                 hops.push(RouteHop {
5257                         pubkey: nodes[2].node.get_our_node_id(),
5258                         short_channel_id: chan_2.0.contents.short_channel_id,
5259                         fee_msat: 0,
5260                         cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
5261                 });
5262                 hops.push(RouteHop {
5263                         pubkey: nodes[3].node.get_our_node_id(),
5264                         short_channel_id: chan_3.0.contents.short_channel_id,
5265                         fee_msat: 0,
5266                         cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
5267                 });
5268                 hops.push(RouteHop {
5269                         pubkey: nodes[1].node.get_our_node_id(),
5270                         short_channel_id: chan_4.0.contents.short_channel_id,
5271                         fee_msat: 1000000,
5272                         cltv_expiry_delta: TEST_FINAL_CLTV,
5273                 });
5274                 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;
5275                 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;
5276                 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
5277
5278                 let mut hops = Vec::with_capacity(3);
5279                 hops.push(RouteHop {
5280                         pubkey: nodes[3].node.get_our_node_id(),
5281                         short_channel_id: chan_4.0.contents.short_channel_id,
5282                         fee_msat: 0,
5283                         cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
5284                 });
5285                 hops.push(RouteHop {
5286                         pubkey: nodes[2].node.get_our_node_id(),
5287                         short_channel_id: chan_3.0.contents.short_channel_id,
5288                         fee_msat: 0,
5289                         cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
5290                 });
5291                 hops.push(RouteHop {
5292                         pubkey: nodes[1].node.get_our_node_id(),
5293                         short_channel_id: chan_2.0.contents.short_channel_id,
5294                         fee_msat: 1000000,
5295                         cltv_expiry_delta: TEST_FINAL_CLTV,
5296                 });
5297                 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;
5298                 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;
5299                 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
5300
5301                 // Claim the rebalances...
5302                 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
5303                 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
5304
5305                 // Add a duplicate new channel from 2 to 4
5306                 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3);
5307
5308                 // Send some payments across both channels
5309                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5310                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5311                 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5312
5313                 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
5314
5315                 //TODO: Test that routes work again here as we've been notified that the channel is full
5316
5317                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
5318                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
5319                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
5320
5321                 // Close down the channels...
5322                 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
5323                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
5324                 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
5325                 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
5326                 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
5327         }
5328
5329         #[test]
5330         fn duplicate_htlc_test() {
5331                 // Test that we accept duplicate payment_hash HTLCs across the network and that
5332                 // claiming/failing them are all separate and don't effect each other
5333                 let mut nodes = create_network(6);
5334
5335                 // Create some initial channels to route via 3 to 4/5 from 0/1/2
5336                 create_announced_chan_between_nodes(&nodes, 0, 3);
5337                 create_announced_chan_between_nodes(&nodes, 1, 3);
5338                 create_announced_chan_between_nodes(&nodes, 2, 3);
5339                 create_announced_chan_between_nodes(&nodes, 3, 4);
5340                 create_announced_chan_between_nodes(&nodes, 3, 5);
5341
5342                 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
5343
5344                 *nodes[0].network_payment_count.borrow_mut() -= 1;
5345                 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
5346
5347                 *nodes[0].network_payment_count.borrow_mut() -= 1;
5348                 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
5349
5350                 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
5351                 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
5352                 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
5353         }
5354
5355         #[derive(PartialEq)]
5356         enum HTLCType { NONE, TIMEOUT, SUCCESS }
5357         /// Tests that the given node has broadcast transactions for the given Channel
5358         ///
5359         /// First checks that the latest local commitment tx has been broadcast, unless an explicit
5360         /// commitment_tx is provided, which may be used to test that a remote commitment tx was
5361         /// broadcast and the revoked outputs were claimed.
5362         ///
5363         /// Next tests that there is (or is not) a transaction that spends the commitment transaction
5364         /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
5365         ///
5366         /// All broadcast transactions must be accounted for in one of the above three types of we'll
5367         /// also fail.
5368         fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
5369                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5370                 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
5371
5372                 let mut res = Vec::with_capacity(2);
5373                 node_txn.retain(|tx| {
5374                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
5375                                 check_spends!(tx, chan.3.clone());
5376                                 if commitment_tx.is_none() {
5377                                         res.push(tx.clone());
5378                                 }
5379                                 false
5380                         } else { true }
5381                 });
5382                 if let Some(explicit_tx) = commitment_tx {
5383                         res.push(explicit_tx.clone());
5384                 }
5385
5386                 assert_eq!(res.len(), 1);
5387
5388                 if has_htlc_tx != HTLCType::NONE {
5389                         node_txn.retain(|tx| {
5390                                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
5391                                         check_spends!(tx, res[0].clone());
5392                                         if has_htlc_tx == HTLCType::TIMEOUT {
5393                                                 assert!(tx.lock_time != 0);
5394                                         } else {
5395                                                 assert!(tx.lock_time == 0);
5396                                         }
5397                                         res.push(tx.clone());
5398                                         false
5399                                 } else { true }
5400                         });
5401                         assert!(res.len() == 2 || res.len() == 3);
5402                         if res.len() == 3 {
5403                                 assert_eq!(res[1], res[2]);
5404                         }
5405                 }
5406
5407                 assert!(node_txn.is_empty());
5408                 res
5409         }
5410
5411         /// Tests that the given node has broadcast a claim transaction against the provided revoked
5412         /// HTLC transaction.
5413         fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
5414                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5415                 assert_eq!(node_txn.len(), 1);
5416                 node_txn.retain(|tx| {
5417                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
5418                                 check_spends!(tx, revoked_tx.clone());
5419                                 false
5420                         } else { true }
5421                 });
5422                 assert!(node_txn.is_empty());
5423         }
5424
5425         fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
5426                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5427
5428                 assert!(node_txn.len() >= 1);
5429                 assert_eq!(node_txn[0].input.len(), 1);
5430                 let mut found_prev = false;
5431
5432                 for tx in prev_txn {
5433                         if node_txn[0].input[0].previous_output.txid == tx.txid() {
5434                                 check_spends!(node_txn[0], tx.clone());
5435                                 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
5436                                 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
5437
5438                                 found_prev = true;
5439                                 break;
5440                         }
5441                 }
5442                 assert!(found_prev);
5443
5444                 let mut res = Vec::new();
5445                 mem::swap(&mut *node_txn, &mut res);
5446                 res
5447         }
5448
5449         fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
5450                 let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
5451                 assert_eq!(events_1.len(), 1);
5452                 let as_update = match events_1[0] {
5453                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5454                                 msg.clone()
5455                         },
5456                         _ => panic!("Unexpected event"),
5457                 };
5458
5459                 let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
5460                 assert_eq!(events_2.len(), 1);
5461                 let bs_update = match events_2[0] {
5462                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5463                                 msg.clone()
5464                         },
5465                         _ => panic!("Unexpected event"),
5466                 };
5467
5468                 for node in nodes {
5469                         node.router.handle_channel_update(&as_update).unwrap();
5470                         node.router.handle_channel_update(&bs_update).unwrap();
5471                 }
5472         }
5473
5474         macro_rules! expect_pending_htlcs_forwardable {
5475                 ($node: expr) => {{
5476                         let events = $node.node.get_and_clear_pending_events();
5477                         assert_eq!(events.len(), 1);
5478                         match events[0] {
5479                                 Event::PendingHTLCsForwardable { .. } => { },
5480                                 _ => panic!("Unexpected event"),
5481                         };
5482                         $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
5483                         $node.node.process_pending_htlc_forwards();
5484                 }}
5485         }
5486
5487         fn do_channel_reserve_test(test_recv: bool) {
5488                 use util::rng;
5489                 use std::sync::atomic::Ordering;
5490                 use ln::msgs::HandleError;
5491
5492                 macro_rules! get_channel_value_stat {
5493                         ($node: expr, $channel_id: expr) => {{
5494                                 let chan_lock = $node.node.channel_state.lock().unwrap();
5495                                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
5496                                 chan.get_value_stat()
5497                         }}
5498                 }
5499
5500                 let mut nodes = create_network(3);
5501                 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001);
5502                 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001);
5503
5504                 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
5505                 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
5506
5507                 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
5508                 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
5509
5510                 macro_rules! get_route_and_payment_hash {
5511                         ($recv_value: expr) => {{
5512                                 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
5513                                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5514                                 (route, payment_hash, payment_preimage)
5515                         }}
5516                 };
5517
5518                 macro_rules! expect_forward {
5519                         ($node: expr) => {{
5520                                 let mut events = $node.node.get_and_clear_pending_msg_events();
5521                                 assert_eq!(events.len(), 1);
5522                                 check_added_monitors!($node, 1);
5523                                 let payment_event = SendEvent::from_event(events.remove(0));
5524                                 payment_event
5525                         }}
5526                 }
5527
5528                 macro_rules! expect_payment_received {
5529                         ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
5530                                 let events = $node.node.get_and_clear_pending_events();
5531                                 assert_eq!(events.len(), 1);
5532                                 match events[0] {
5533                                         Event::PaymentReceived { ref payment_hash, amt } => {
5534                                                 assert_eq!($expected_payment_hash, *payment_hash);
5535                                                 assert_eq!($expected_recv_value, amt);
5536                                         },
5537                                         _ => panic!("Unexpected event"),
5538                                 }
5539                         }
5540                 };
5541
5542                 let feemsat = 239; // somehow we know?
5543                 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
5544
5545                 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
5546
5547                 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
5548                 {
5549                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
5550                         assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
5551                         let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
5552                         match err {
5553                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
5554                                 _ => panic!("Unknown error variants"),
5555                         }
5556                 }
5557
5558                 let mut htlc_id = 0;
5559                 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
5560                 // nodes[0]'s wealth
5561                 loop {
5562                         let amt_msat = recv_value_0 + total_fee_msat;
5563                         if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
5564                                 break;
5565                         }
5566                         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
5567                         htlc_id += 1;
5568
5569                         let (stat01_, stat11_, stat12_, stat22_) = (
5570                                 get_channel_value_stat!(nodes[0], chan_1.2),
5571                                 get_channel_value_stat!(nodes[1], chan_1.2),
5572                                 get_channel_value_stat!(nodes[1], chan_2.2),
5573                                 get_channel_value_stat!(nodes[2], chan_2.2),
5574                         );
5575
5576                         assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
5577                         assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
5578                         assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
5579                         assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
5580                         stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
5581                 }
5582
5583                 {
5584                         let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
5585                         // attempt to get channel_reserve violation
5586                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
5587                         let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
5588                         match err {
5589                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5590                                 _ => panic!("Unknown error variants"),
5591                         }
5592                 }
5593
5594                 // adding pending output
5595                 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
5596                 let amt_msat_1 = recv_value_1 + total_fee_msat;
5597
5598                 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
5599                 let payment_event_1 = {
5600                         nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
5601                         check_added_monitors!(nodes[0], 1);
5602
5603                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5604                         assert_eq!(events.len(), 1);
5605                         SendEvent::from_event(events.remove(0))
5606                 };
5607                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]).unwrap();
5608
5609                 // channel reserve test with htlc pending output > 0
5610                 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
5611                 {
5612                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5613                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5614                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5615                                 _ => panic!("Unknown error variants"),
5616                         }
5617                 }
5618
5619                 {
5620                         // test channel_reserve test on nodes[1] side
5621                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5622
5623                         // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
5624                         let secp_ctx = Secp256k1::new();
5625                         let session_priv = SecretKey::from_slice(&secp_ctx, &{
5626                                 let mut session_key = [0; 32];
5627                                 rng::fill_bytes(&mut session_key);
5628                                 session_key
5629                         }).expect("RNG is bad!");
5630
5631                         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5632                         let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
5633                         let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height).unwrap();
5634                         let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
5635                         let msg = msgs::UpdateAddHTLC {
5636                                 channel_id: chan_1.2,
5637                                 htlc_id,
5638                                 amount_msat: htlc_msat,
5639                                 payment_hash: our_payment_hash,
5640                                 cltv_expiry: htlc_cltv,
5641                                 onion_routing_packet: onion_packet,
5642                         };
5643
5644                         if test_recv {
5645                                 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).err().unwrap();
5646                                 match err {
5647                                         HandleError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
5648                                 }
5649                                 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
5650                                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5651                                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5652                                 let channel_close_broadcast = nodes[1].node.get_and_clear_pending_msg_events();
5653                                 assert_eq!(channel_close_broadcast.len(), 1);
5654                                 match channel_close_broadcast[0] {
5655                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5656                                                 assert_eq!(msg.contents.flags & 2, 2);
5657                                         },
5658                                         _ => panic!("Unexpected event"),
5659                                 }
5660                                 return;
5661                         }
5662                 }
5663
5664                 // split the rest to test holding cell
5665                 let recv_value_21 = recv_value_2/2;
5666                 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
5667                 {
5668                         let stat = get_channel_value_stat!(nodes[0], chan_1.2);
5669                         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);
5670                 }
5671
5672                 // now see if they go through on both sides
5673                 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
5674                 // but this will stuck in the holding cell
5675                 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
5676                 check_added_monitors!(nodes[0], 0);
5677                 let events = nodes[0].node.get_and_clear_pending_events();
5678                 assert_eq!(events.len(), 0);
5679
5680                 // test with outbound holding cell amount > 0
5681                 {
5682                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
5683                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5684                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5685                                 _ => panic!("Unknown error variants"),
5686                         }
5687                 }
5688
5689                 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
5690                 // this will also stuck in the holding cell
5691                 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
5692                 check_added_monitors!(nodes[0], 0);
5693                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
5694                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5695
5696                 // flush the pending htlc
5697                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg).unwrap();
5698                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5699                 check_added_monitors!(nodes[1], 1);
5700
5701                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
5702                 check_added_monitors!(nodes[0], 1);
5703                 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5704
5705                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed).unwrap();
5706                 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
5707                 // No commitment_signed so get_event_msg's assert(len == 1) passes
5708                 check_added_monitors!(nodes[0], 1);
5709
5710                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
5711                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5712                 check_added_monitors!(nodes[1], 1);
5713
5714                 expect_pending_htlcs_forwardable!(nodes[1]);
5715
5716                 let ref payment_event_11 = expect_forward!(nodes[1]);
5717                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]).unwrap();
5718                 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
5719
5720                 expect_pending_htlcs_forwardable!(nodes[2]);
5721                 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
5722
5723                 // flush the htlcs in the holding cell
5724                 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
5725                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]).unwrap();
5726                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]).unwrap();
5727                 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
5728                 expect_pending_htlcs_forwardable!(nodes[1]);
5729
5730                 let ref payment_event_3 = expect_forward!(nodes[1]);
5731                 assert_eq!(payment_event_3.msgs.len(), 2);
5732                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]).unwrap();
5733                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]).unwrap();
5734
5735                 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
5736                 expect_pending_htlcs_forwardable!(nodes[2]);
5737
5738                 let events = nodes[2].node.get_and_clear_pending_events();
5739                 assert_eq!(events.len(), 2);
5740                 match events[0] {
5741                         Event::PaymentReceived { ref payment_hash, amt } => {
5742                                 assert_eq!(our_payment_hash_21, *payment_hash);
5743                                 assert_eq!(recv_value_21, amt);
5744                         },
5745                         _ => panic!("Unexpected event"),
5746                 }
5747                 match events[1] {
5748                         Event::PaymentReceived { ref payment_hash, amt } => {
5749                                 assert_eq!(our_payment_hash_22, *payment_hash);
5750                                 assert_eq!(recv_value_22, amt);
5751                         },
5752                         _ => panic!("Unexpected event"),
5753                 }
5754
5755                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
5756                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
5757                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
5758
5759                 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);
5760                 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
5761                 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
5762                 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
5763
5764                 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
5765                 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
5766         }
5767
5768         #[test]
5769         fn channel_reserve_test() {
5770                 do_channel_reserve_test(false);
5771                 do_channel_reserve_test(true);
5772         }
5773
5774         #[test]
5775         fn channel_monitor_network_test() {
5776                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5777                 // tests that ChannelMonitor is able to recover from various states.
5778                 let nodes = create_network(5);
5779
5780                 // Create some initial channels
5781                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5782                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5783                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5784                 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5785
5786                 // Rebalance the network a bit by relaying one payment through all the channels...
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                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5791
5792                 // Simple case with no pending HTLCs:
5793                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
5794                 {
5795                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
5796                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5797                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5798                         test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
5799                 }
5800                 get_announce_close_broadcast_events(&nodes, 0, 1);
5801                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5802                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5803
5804                 // One pending HTLC is discarded by the force-close:
5805                 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
5806
5807                 // Simple case of one pending HTLC to HTLC-Timeout
5808                 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
5809                 {
5810                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
5811                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5812                         nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5813                         test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
5814                 }
5815                 get_announce_close_broadcast_events(&nodes, 1, 2);
5816                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5817                 assert_eq!(nodes[2].node.list_channels().len(), 1);
5818
5819                 macro_rules! claim_funds {
5820                         ($node: expr, $prev_node: expr, $preimage: expr) => {
5821                                 {
5822                                         assert!($node.node.claim_funds($preimage));
5823                                         check_added_monitors!($node, 1);
5824
5825                                         let events = $node.node.get_and_clear_pending_msg_events();
5826                                         assert_eq!(events.len(), 1);
5827                                         match events[0] {
5828                                                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
5829                                                         assert!(update_add_htlcs.is_empty());
5830                                                         assert!(update_fail_htlcs.is_empty());
5831                                                         assert_eq!(*node_id, $prev_node.node.get_our_node_id());
5832                                                 },
5833                                                 _ => panic!("Unexpected event"),
5834                                         };
5835                                 }
5836                         }
5837                 }
5838
5839                 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
5840                 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
5841                 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
5842                 {
5843                         let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
5844
5845                         // Claim the payment on nodes[3], giving it knowledge of the preimage
5846                         claim_funds!(nodes[3], nodes[2], payment_preimage_1);
5847
5848                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5849                         nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
5850
5851                         check_preimage_claim(&nodes[3], &node_txn);
5852                 }
5853                 get_announce_close_broadcast_events(&nodes, 2, 3);
5854                 assert_eq!(nodes[2].node.list_channels().len(), 0);
5855                 assert_eq!(nodes[3].node.list_channels().len(), 1);
5856
5857                 { // Cheat and reset nodes[4]'s height to 1
5858                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5859                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![] }, 1);
5860                 }
5861
5862                 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
5863                 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
5864                 // One pending HTLC to time out:
5865                 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
5866                 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
5867                 // buffer space).
5868
5869                 {
5870                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5871                         nodes[3].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5872                         for i in 3..TEST_FINAL_CLTV + 2 + HTLC_FAIL_TIMEOUT_BLOCKS + 1 {
5873                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5874                                 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5875                         }
5876
5877                         let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
5878
5879                         // Claim the payment on nodes[4], giving it knowledge of the preimage
5880                         claim_funds!(nodes[4], nodes[3], payment_preimage_2);
5881
5882                         header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5883                         nodes[4].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5884                         for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
5885                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5886                                 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5887                         }
5888
5889                         test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
5890
5891                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5892                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
5893
5894                         check_preimage_claim(&nodes[4], &node_txn);
5895                 }
5896                 get_announce_close_broadcast_events(&nodes, 3, 4);
5897                 assert_eq!(nodes[3].node.list_channels().len(), 0);
5898                 assert_eq!(nodes[4].node.list_channels().len(), 0);
5899         }
5900
5901         #[test]
5902         fn test_justice_tx() {
5903                 // Test justice txn built on revoked HTLC-Success tx, against both sides
5904
5905                 let nodes = create_network(2);
5906                 // Create some new channels:
5907                 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
5908
5909                 // A pending HTLC which will be revoked:
5910                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5911                 // Get the will-be-revoked local txn from nodes[0]
5912                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5913                 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
5914                 assert_eq!(revoked_local_txn[0].input.len(), 1);
5915                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
5916                 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
5917                 assert_eq!(revoked_local_txn[1].input.len(), 1);
5918                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
5919                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
5920                 // Revoke the old state
5921                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
5922
5923                 {
5924                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5925                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5926                         {
5927                                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5928                                 assert_eq!(node_txn.len(), 3);
5929                                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5930                                 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
5931
5932                                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5933                                 node_txn.swap_remove(0);
5934                         }
5935                         test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
5936
5937                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5938                         let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
5939                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5940                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5941                         test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
5942                 }
5943                 get_announce_close_broadcast_events(&nodes, 0, 1);
5944
5945                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5946                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5947
5948                 // We test justice_tx build by A on B's revoked HTLC-Success tx
5949                 // Create some new channels:
5950                 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
5951
5952                 // A pending HTLC which will be revoked:
5953                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5954                 // Get the will-be-revoked local txn from B
5955                 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5956                 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
5957                 assert_eq!(revoked_local_txn[0].input.len(), 1);
5958                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
5959                 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
5960                 // Revoke the old state
5961                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
5962                 {
5963                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5964                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5965                         {
5966                                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5967                                 assert_eq!(node_txn.len(), 3);
5968                                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5969                                 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
5970
5971                                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5972                                 node_txn.swap_remove(0);
5973                         }
5974                         test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
5975
5976                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5977                         let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
5978                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5979                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5980                         test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone());
5981                 }
5982                 get_announce_close_broadcast_events(&nodes, 0, 1);
5983                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5984                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5985         }
5986
5987         #[test]
5988         fn revoked_output_claim() {
5989                 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
5990                 // transaction is broadcast by its counterparty
5991                 let nodes = create_network(2);
5992                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5993                 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
5994                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5995                 assert_eq!(revoked_local_txn.len(), 1);
5996                 // Only output is the full channel value back to nodes[0]:
5997                 assert_eq!(revoked_local_txn[0].output.len(), 1);
5998                 // Send a payment through, updating everyone's latest commitment txn
5999                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
6000
6001                 // Inform nodes[1] that nodes[0] broadcast a stale tx
6002                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6003                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6004                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6005                 assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
6006
6007                 assert_eq!(node_txn[0], node_txn[2]);
6008
6009                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
6010                 check_spends!(node_txn[1], chan_1.3.clone());
6011
6012                 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
6013                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6014                 get_announce_close_broadcast_events(&nodes, 0, 1);
6015         }
6016
6017         #[test]
6018         fn claim_htlc_outputs_shared_tx() {
6019                 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
6020                 let nodes = create_network(2);
6021
6022                 // Create some new channel:
6023                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6024
6025                 // Rebalance the network to generate htlc in the two directions
6026                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6027                 // 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
6028                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6029                 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6030
6031                 // Get the will-be-revoked local txn from node[0]
6032                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6033                 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
6034                 assert_eq!(revoked_local_txn[0].input.len(), 1);
6035                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
6036                 assert_eq!(revoked_local_txn[1].input.len(), 1);
6037                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
6038                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
6039                 check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
6040
6041                 //Revoke the old state
6042                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6043
6044                 {
6045                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6046                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6047                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6048
6049                         let events = nodes[1].node.get_and_clear_pending_events();
6050                         assert_eq!(events.len(), 1);
6051                         match events[0] {
6052                                 Event::PaymentFailed { payment_hash, .. } => {
6053                                         assert_eq!(payment_hash, payment_hash_2);
6054                                 },
6055                                 _ => panic!("Unexpected event"),
6056                         }
6057
6058                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6059                         assert_eq!(node_txn.len(), 4);
6060
6061                         assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
6062                         check_spends!(node_txn[0], revoked_local_txn[0].clone());
6063
6064                         assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
6065
6066                         let mut witness_lens = BTreeSet::new();
6067                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6068                         witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
6069                         witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
6070                         assert_eq!(witness_lens.len(), 3);
6071                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6072                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
6073                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
6074
6075                         // Next nodes[1] broadcasts its current local tx state:
6076                         assert_eq!(node_txn[1].input.len(), 1);
6077                         assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
6078
6079                         assert_eq!(node_txn[2].input.len(), 1);
6080                         let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
6081                         assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
6082                         assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
6083                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6084                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
6085                 }
6086                 get_announce_close_broadcast_events(&nodes, 0, 1);
6087                 assert_eq!(nodes[0].node.list_channels().len(), 0);
6088                 assert_eq!(nodes[1].node.list_channels().len(), 0);
6089         }
6090
6091         #[test]
6092         fn claim_htlc_outputs_single_tx() {
6093                 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
6094                 let nodes = create_network(2);
6095
6096                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6097
6098                 // Rebalance the network to generate htlc in the two directions
6099                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6100                 // 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
6101                 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
6102                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6103                 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6104
6105                 // Get the will-be-revoked local txn from node[0]
6106                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6107
6108                 //Revoke the old state
6109                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6110
6111                 {
6112                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6113                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6114                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6115
6116                         let events = nodes[1].node.get_and_clear_pending_events();
6117                         assert_eq!(events.len(), 1);
6118                         match events[0] {
6119                                 Event::PaymentFailed { payment_hash, .. } => {
6120                                         assert_eq!(payment_hash, payment_hash_2);
6121                                 },
6122                                 _ => panic!("Unexpected event"),
6123                         }
6124
6125                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6126                         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)
6127
6128                         assert_eq!(node_txn[0], node_txn[7]);
6129                         assert_eq!(node_txn[1], node_txn[8]);
6130                         assert_eq!(node_txn[2], node_txn[9]);
6131                         assert_eq!(node_txn[3], node_txn[10]);
6132                         assert_eq!(node_txn[4], node_txn[11]);
6133                         assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcated by ChannelManger
6134                         assert_eq!(node_txn[4], node_txn[6]);
6135
6136                         assert_eq!(node_txn[0].input.len(), 1);
6137                         assert_eq!(node_txn[1].input.len(), 1);
6138                         assert_eq!(node_txn[2].input.len(), 1);
6139
6140                         let mut revoked_tx_map = HashMap::new();
6141                         revoked_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
6142                         node_txn[0].verify(&revoked_tx_map).unwrap();
6143                         node_txn[1].verify(&revoked_tx_map).unwrap();
6144                         node_txn[2].verify(&revoked_tx_map).unwrap();
6145
6146                         let mut witness_lens = BTreeSet::new();
6147                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6148                         witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
6149                         witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
6150                         assert_eq!(witness_lens.len(), 3);
6151                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6152                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
6153                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
6154
6155                         assert_eq!(node_txn[3].input.len(), 1);
6156                         check_spends!(node_txn[3], chan_1.3.clone());
6157
6158                         assert_eq!(node_txn[4].input.len(), 1);
6159                         let witness_script = node_txn[4].input[0].witness.last().unwrap();
6160                         assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
6161                         assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
6162                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6163                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
6164                 }
6165                 get_announce_close_broadcast_events(&nodes, 0, 1);
6166                 assert_eq!(nodes[0].node.list_channels().len(), 0);
6167                 assert_eq!(nodes[1].node.list_channels().len(), 0);
6168         }
6169
6170         #[test]
6171         fn test_htlc_on_chain_success() {
6172                 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
6173                 // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
6174                 // broadcasting the right event to other nodes in payment path.
6175                 // A --------------------> B ----------------------> C (preimage)
6176                 // First, C should claim the HTLC output via HTLC-Success when its own latest local
6177                 // commitment transaction was broadcast.
6178                 // Then, B should learn the preimage from said transactions, attempting to claim backwards
6179                 // towards B.
6180                 // B should be able to claim via preimage if A then broadcasts its local tx.
6181                 // Finally, when A sees B's latest local commitment transaction it should be able to claim
6182                 // the HTLC output via the preimage it learned (which, once confirmed should generate a
6183                 // PaymentSent event).
6184
6185                 let nodes = create_network(3);
6186
6187                 // Create some initial channels
6188                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6189                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6190
6191                 // Rebalance the network a bit by relaying one payment through all the channels...
6192                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6193                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6194
6195                 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
6196                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6197
6198                 // Broadcast legit commitment tx from C on B's chain
6199                 // Broadcast HTLC Success transation by C on received output from C's commitment tx on B's chain
6200                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6201                 assert_eq!(commitment_tx.len(), 1);
6202                 check_spends!(commitment_tx[0], chan_2.3.clone());
6203                 nodes[2].node.claim_funds(our_payment_preimage);
6204                 check_added_monitors!(nodes[2], 1);
6205                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6206                 assert!(updates.update_add_htlcs.is_empty());
6207                 assert!(updates.update_fail_htlcs.is_empty());
6208                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6209                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
6210
6211                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6212                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6213                 assert_eq!(events.len(), 1);
6214                 match events[0] {
6215                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6216                         _ => panic!("Unexpected event"),
6217                 }
6218                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
6219                 assert_eq!(node_txn.len(), 3);
6220                 assert_eq!(node_txn[1], commitment_tx[0]);
6221                 assert_eq!(node_txn[0], node_txn[2]);
6222                 check_spends!(node_txn[0], commitment_tx[0].clone());
6223                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6224                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6225                 assert_eq!(node_txn[0].lock_time, 0);
6226
6227                 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
6228                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: node_txn}, 1);
6229                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6230                 {
6231                         let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
6232                         assert_eq!(added_monitors.len(), 1);
6233                         assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
6234                         added_monitors.clear();
6235                 }
6236                 assert_eq!(events.len(), 2);
6237                 match events[0] {
6238                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6239                         _ => panic!("Unexpected event"),
6240                 }
6241                 match events[1] {
6242                         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, .. } } => {
6243                                 assert!(update_add_htlcs.is_empty());
6244                                 assert!(update_fail_htlcs.is_empty());
6245                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6246                                 assert!(update_fail_malformed_htlcs.is_empty());
6247                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6248                         },
6249                         _ => panic!("Unexpected event"),
6250                 };
6251                 {
6252                         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
6253                         // commitment transaction with a corresponding HTLC-Timeout transaction, as well as a
6254                         // timeout-claim of the output that nodes[2] just claimed via success.
6255                         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)
6256                         assert_eq!(node_txn.len(), 4);
6257                         assert_eq!(node_txn[0], node_txn[3]);
6258                         check_spends!(node_txn[0], commitment_tx[0].clone());
6259                         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6260                         assert_ne!(node_txn[0].lock_time, 0);
6261                         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
6262                         check_spends!(node_txn[1], chan_2.3.clone());
6263                         check_spends!(node_txn[2], node_txn[1].clone());
6264                         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6265                         assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6266                         assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6267                         assert_ne!(node_txn[2].lock_time, 0);
6268                         node_txn.clear();
6269                 }
6270
6271                 // Broadcast legit commitment tx from A on B's chain
6272                 // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
6273                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6274                 check_spends!(commitment_tx[0], chan_1.3.clone());
6275                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6276                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6277                 assert_eq!(events.len(), 1);
6278                 match events[0] {
6279                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6280                         _ => panic!("Unexpected event"),
6281                 }
6282                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 1 (HTLC-Success) * 2 (block-rescan)
6283                 assert_eq!(node_txn.len(), 3);
6284                 assert_eq!(node_txn[0], node_txn[2]);
6285                 check_spends!(node_txn[0], commitment_tx[0].clone());
6286                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6287                 assert_eq!(node_txn[0].lock_time, 0);
6288                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
6289                 check_spends!(node_txn[1], chan_1.3.clone());
6290                 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6291                 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
6292                 // we already checked the same situation with A.
6293
6294                 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
6295                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
6296                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6297                 assert_eq!(events.len(), 1);
6298                 match events[0] {
6299                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6300                         _ => panic!("Unexpected event"),
6301                 }
6302                 let events = nodes[0].node.get_and_clear_pending_events();
6303                 assert_eq!(events.len(), 1);
6304                 match events[0] {
6305                         Event::PaymentSent { payment_preimage } => {
6306                                 assert_eq!(payment_preimage, our_payment_preimage);
6307                         },
6308                         _ => panic!("Unexpected event"),
6309                 }
6310                 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)
6311                 assert_eq!(node_txn.len(), 4);
6312                 assert_eq!(node_txn[0], node_txn[3]);
6313                 check_spends!(node_txn[0], commitment_tx[0].clone());
6314                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6315                 assert_ne!(node_txn[0].lock_time, 0);
6316                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6317                 check_spends!(node_txn[1], chan_1.3.clone());
6318                 check_spends!(node_txn[2], node_txn[1].clone());
6319                 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6320                 assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6321                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6322                 assert_ne!(node_txn[2].lock_time, 0);
6323         }
6324
6325         #[test]
6326         fn test_htlc_on_chain_timeout() {
6327                 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
6328                 // ChainWatchInterface and timeout the HTLC  bacward accordingly. So here we test that ChannelManager is
6329                 // broadcasting the right event to other nodes in payment path.
6330                 // A ------------------> B ----------------------> C (timeout)
6331                 //    B's commitment tx                 C's commitment tx
6332                 //            \                                  \
6333                 //         B's HTLC timeout tx               B's timeout tx
6334
6335                 let nodes = create_network(3);
6336
6337                 // Create some intial channels
6338                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6339                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6340
6341                 // Rebalance the network a bit by relaying one payment thorugh all the channels...
6342                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6343                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6344
6345                 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
6346                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6347
6348                 // Brodacast legit commitment tx from C on B's chain
6349                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6350                 check_spends!(commitment_tx[0], chan_2.3.clone());
6351                 nodes[2].node.fail_htlc_backwards(&payment_hash, PaymentFailReason::PreimageUnknown);
6352                 {
6353                         let mut added_monitors = nodes[2].chan_monitor.added_monitors.lock().unwrap();
6354                         assert_eq!(added_monitors.len(), 1);
6355                         added_monitors.clear();
6356                 }
6357                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6358                 assert_eq!(events.len(), 1);
6359                 match events[0] {
6360                         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, .. } } => {
6361                                 assert!(update_add_htlcs.is_empty());
6362                                 assert!(!update_fail_htlcs.is_empty());
6363                                 assert!(update_fulfill_htlcs.is_empty());
6364                                 assert!(update_fail_malformed_htlcs.is_empty());
6365                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
6366                         },
6367                         _ => panic!("Unexpected event"),
6368                 };
6369                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6370                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6371                 assert_eq!(events.len(), 1);
6372                 match events[0] {
6373                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6374                         _ => panic!("Unexpected event"),
6375                 }
6376                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
6377                 assert_eq!(node_txn.len(), 1);
6378                 check_spends!(node_txn[0], chan_2.3.clone());
6379                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
6380
6381                 // Broadcast timeout transaction by B on received output fron C's commitment tx on B's chain
6382                 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
6383                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6384                 let timeout_tx;
6385                 {
6386                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6387                         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)
6388                         assert_eq!(node_txn[0], node_txn[5]);
6389                         assert_eq!(node_txn[1], node_txn[6]);
6390                         assert_eq!(node_txn[2], node_txn[7]);
6391                         check_spends!(node_txn[0], commitment_tx[0].clone());
6392                         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6393                         check_spends!(node_txn[1], chan_2.3.clone());
6394                         check_spends!(node_txn[2], node_txn[1].clone());
6395                         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6396                         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6397                         check_spends!(node_txn[3], chan_2.3.clone());
6398                         check_spends!(node_txn[4], node_txn[3].clone());
6399                         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
6400                         assert_eq!(node_txn[4].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6401                         timeout_tx = node_txn[0].clone();
6402                         node_txn.clear();
6403                 }
6404
6405                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![timeout_tx]}, 1);
6406                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6407                 check_added_monitors!(nodes[1], 1);
6408                 assert_eq!(events.len(), 2);
6409                 match events[0] {
6410                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6411                         _ => panic!("Unexpected event"),
6412                 }
6413                 match events[1] {
6414                         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, .. } } => {
6415                                 assert!(update_add_htlcs.is_empty());
6416                                 assert!(!update_fail_htlcs.is_empty());
6417                                 assert!(update_fulfill_htlcs.is_empty());
6418                                 assert!(update_fail_malformed_htlcs.is_empty());
6419                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6420                         },
6421                         _ => panic!("Unexpected event"),
6422                 };
6423                 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
6424                 assert_eq!(node_txn.len(), 0);
6425
6426                 // Broadcast legit commitment tx from B on A's chain
6427                 let commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6428                 check_spends!(commitment_tx[0], chan_1.3.clone());
6429
6430                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6431                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6432                 assert_eq!(events.len(), 1);
6433                 match events[0] {
6434                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6435                         _ => panic!("Unexpected event"),
6436                 }
6437                 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
6438                 assert_eq!(node_txn.len(), 4);
6439                 assert_eq!(node_txn[0], node_txn[3]);
6440                 check_spends!(node_txn[0], commitment_tx[0].clone());
6441                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6442                 check_spends!(node_txn[1], chan_1.3.clone());
6443                 check_spends!(node_txn[2], node_txn[1].clone());
6444                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6445                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6446         }
6447
6448         #[test]
6449         fn test_simple_commitment_revoked_fail_backward() {
6450                 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
6451                 // and fail backward accordingly.
6452
6453                 let nodes = create_network(3);
6454
6455                 // Create some initial channels
6456                 create_announced_chan_between_nodes(&nodes, 0, 1);
6457                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6458
6459                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6460                 // Get the will-be-revoked local txn from nodes[2]
6461                 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6462                 // Revoke the old state
6463                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6464
6465                 route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6466
6467                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6468                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6469                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6470                 check_added_monitors!(nodes[1], 1);
6471                 assert_eq!(events.len(), 2);
6472                 match events[0] {
6473                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6474                         _ => panic!("Unexpected event"),
6475                 }
6476                 match events[1] {
6477                         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, .. } } => {
6478                                 assert!(update_add_htlcs.is_empty());
6479                                 assert_eq!(update_fail_htlcs.len(), 1);
6480                                 assert!(update_fulfill_htlcs.is_empty());
6481                                 assert!(update_fail_malformed_htlcs.is_empty());
6482                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6483
6484                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6485                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6486
6487                                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6488                                 assert_eq!(events.len(), 1);
6489                                 match events[0] {
6490                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6491                                         _ => panic!("Unexpected event"),
6492                                 }
6493                                 let events = nodes[0].node.get_and_clear_pending_events();
6494                                 assert_eq!(events.len(), 1);
6495                                 match events[0] {
6496                                         Event::PaymentFailed { .. } => {},
6497                                         _ => panic!("Unexpected event"),
6498                                 }
6499                         },
6500                         _ => panic!("Unexpected event"),
6501                 }
6502         }
6503
6504         fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool) {
6505                 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
6506                 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
6507                 // commitment transaction anymore.
6508                 // To do this, we have the peer which will broadcast a revoked commitment transaction send
6509                 // a number of update_fail/commitment_signed updates without ever sending the RAA in
6510                 // response to our commitment_signed. This is somewhat misbehavior-y, though not
6511                 // technically disallowed and we should probably handle it reasonably.
6512                 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
6513                 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
6514                 // transactions:
6515                 // * Once we move it out of our holding cell/add it, we will immediately include it in a
6516                 //   commitment_signed (implying it will be in the latest remote commitment transaction).
6517                 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
6518                 //   and once they revoke the previous commitment transaction (allowing us to send a new
6519                 //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
6520                 let mut nodes = create_network(3);
6521
6522                 // Create some initial channels
6523                 create_announced_chan_between_nodes(&nodes, 0, 1);
6524                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6525
6526                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6527                 // Get the will-be-revoked local txn from nodes[2]
6528                 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6529                 // Revoke the old state
6530                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6531
6532                 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6533                 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6534                 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6535
6536                 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, PaymentFailReason::PreimageUnknown));
6537                 check_added_monitors!(nodes[2], 1);
6538                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6539                 assert!(updates.update_add_htlcs.is_empty());
6540                 assert!(updates.update_fulfill_htlcs.is_empty());
6541                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6542                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6543                 assert!(updates.update_fee.is_none());
6544                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6545                 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
6546                 // Drop the last RAA from 3 -> 2
6547
6548                 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, PaymentFailReason::PreimageUnknown));
6549                 check_added_monitors!(nodes[2], 1);
6550                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6551                 assert!(updates.update_add_htlcs.is_empty());
6552                 assert!(updates.update_fulfill_htlcs.is_empty());
6553                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6554                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6555                 assert!(updates.update_fee.is_none());
6556                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6557                 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6558                 check_added_monitors!(nodes[1], 1);
6559                 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
6560                 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6561                 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6562                 check_added_monitors!(nodes[2], 1);
6563
6564                 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, PaymentFailReason::PreimageUnknown));
6565                 check_added_monitors!(nodes[2], 1);
6566                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6567                 assert!(updates.update_add_htlcs.is_empty());
6568                 assert!(updates.update_fulfill_htlcs.is_empty());
6569                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6570                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6571                 assert!(updates.update_fee.is_none());
6572                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6573                 // At this point first_payment_hash has dropped out of the latest two commitment
6574                 // transactions that nodes[1] is tracking...
6575                 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6576                 check_added_monitors!(nodes[1], 1);
6577                 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
6578                 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6579                 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6580                 check_added_monitors!(nodes[2], 1);
6581
6582                 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
6583                 // on nodes[2]'s RAA.
6584                 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
6585                 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6586                 nodes[1].node.send_payment(route, fourth_payment_hash).unwrap();
6587                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
6588                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6589                 check_added_monitors!(nodes[1], 0);
6590
6591                 if deliver_bs_raa {
6592                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa).unwrap();
6593                         // One monitor for the new revocation preimage, one as we generate a commitment for
6594                         // nodes[0] to fail first_payment_hash backwards.
6595                         check_added_monitors!(nodes[1], 2);
6596                 }
6597
6598                 let mut failed_htlcs = HashSet::new();
6599                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6600
6601                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6602                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6603
6604                 let events = nodes[1].node.get_and_clear_pending_events();
6605                 assert_eq!(events.len(), 1);
6606                 match events[0] {
6607                         Event::PaymentFailed { ref payment_hash, .. } => {
6608                                 assert_eq!(*payment_hash, fourth_payment_hash);
6609                         },
6610                         _ => panic!("Unexpected event"),
6611                 }
6612
6613                 if !deliver_bs_raa {
6614                         // If we delivered the RAA already then we already failed first_payment_hash backwards.
6615                         check_added_monitors!(nodes[1], 1);
6616                 }
6617
6618                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6619                 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
6620                 match events[if deliver_bs_raa { 2 } else { 0 }] {
6621                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6622                         _ => panic!("Unexpected event"),
6623                 }
6624                 if deliver_bs_raa {
6625                         match events[0] {
6626                                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
6627                                         assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
6628                                         assert_eq!(update_add_htlcs.len(), 1);
6629                                         assert!(update_fulfill_htlcs.is_empty());
6630                                         assert!(update_fail_htlcs.is_empty());
6631                                         assert!(update_fail_malformed_htlcs.is_empty());
6632                                 },
6633                                 _ => panic!("Unexpected event"),
6634                         }
6635                 }
6636                 // Due to the way backwards-failing occurs we do the updates in two steps.
6637                 let updates = match events[1] {
6638                         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, .. } } => {
6639                                 assert!(update_add_htlcs.is_empty());
6640                                 assert_eq!(update_fail_htlcs.len(), 1);
6641                                 assert!(update_fulfill_htlcs.is_empty());
6642                                 assert!(update_fail_malformed_htlcs.is_empty());
6643                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6644
6645                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6646                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
6647                                 check_added_monitors!(nodes[0], 1);
6648                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6649                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6650                                 check_added_monitors!(nodes[1], 1);
6651                                 let bs_second_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6652                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
6653                                 check_added_monitors!(nodes[1], 1);
6654                                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6655                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6656                                 check_added_monitors!(nodes[0], 1);
6657
6658                                 if !deliver_bs_raa {
6659                                         // If we delievered B's RAA we got an unknown preimage error, not something
6660                                         // that we should update our routing table for.
6661                                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6662                                         assert_eq!(events.len(), 1);
6663                                         match events[0] {
6664                                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6665                                                 _ => panic!("Unexpected event"),
6666                                         }
6667                                 }
6668                                 let events = nodes[0].node.get_and_clear_pending_events();
6669                                 assert_eq!(events.len(), 1);
6670                                 match events[0] {
6671                                         Event::PaymentFailed { ref payment_hash, .. } => {
6672                                                 assert!(failed_htlcs.insert(payment_hash.0));
6673                                         },
6674                                         _ => panic!("Unexpected event"),
6675                                 }
6676
6677                                 bs_second_update
6678                         },
6679                         _ => panic!("Unexpected event"),
6680                 };
6681
6682                 assert!(updates.update_add_htlcs.is_empty());
6683                 assert_eq!(updates.update_fail_htlcs.len(), 2);
6684                 assert!(updates.update_fulfill_htlcs.is_empty());
6685                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6686                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6687                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[1]).unwrap();
6688                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6689
6690                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6691                 assert_eq!(events.len(), 2);
6692                 for event in events {
6693                         match event {
6694                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6695                                 _ => panic!("Unexpected event"),
6696                         }
6697                 }
6698
6699                 let events = nodes[0].node.get_and_clear_pending_events();
6700                 assert_eq!(events.len(), 2);
6701                 match events[0] {
6702                         Event::PaymentFailed { ref payment_hash, .. } => {
6703                                 assert!(failed_htlcs.insert(payment_hash.0));
6704                         },
6705                         _ => panic!("Unexpected event"),
6706                 }
6707                 match events[1] {
6708                         Event::PaymentFailed { ref payment_hash, .. } => {
6709                                 assert!(failed_htlcs.insert(payment_hash.0));
6710                         },
6711                         _ => panic!("Unexpected event"),
6712                 }
6713
6714                 assert!(failed_htlcs.contains(&first_payment_hash.0));
6715                 assert!(failed_htlcs.contains(&second_payment_hash.0));
6716                 assert!(failed_htlcs.contains(&third_payment_hash.0));
6717         }
6718
6719         #[test]
6720         fn test_commitment_revoked_fail_backward_exhaustive() {
6721                 do_test_commitment_revoked_fail_backward_exhaustive(false);
6722                 do_test_commitment_revoked_fail_backward_exhaustive(true);
6723         }
6724
6725         #[test]
6726         fn test_htlc_ignore_latest_remote_commitment() {
6727                 // Test that HTLC transactions spending the latest remote commitment transaction are simply
6728                 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
6729                 let nodes = create_network(2);
6730                 create_announced_chan_between_nodes(&nodes, 0, 1);
6731
6732                 route_payment(&nodes[0], &[&nodes[1]], 10000000);
6733                 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
6734                 {
6735                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6736                         assert_eq!(events.len(), 1);
6737                         match events[0] {
6738                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6739                                         assert_eq!(flags & 0b10, 0b10);
6740                                 },
6741                                 _ => panic!("Unexpected event"),
6742                         }
6743                 }
6744
6745                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6746                 assert_eq!(node_txn.len(), 2);
6747
6748                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6749                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6750
6751                 {
6752                         let events = nodes[1].node.get_and_clear_pending_msg_events();
6753                         assert_eq!(events.len(), 1);
6754                         match events[0] {
6755                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6756                                         assert_eq!(flags & 0b10, 0b10);
6757                                 },
6758                                 _ => panic!("Unexpected event"),
6759                         }
6760                 }
6761
6762                 // Duplicate the block_connected call since this may happen due to other listeners
6763                 // registering new transactions
6764                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6765         }
6766
6767         #[test]
6768         fn test_force_close_fail_back() {
6769                 // Check which HTLCs are failed-backwards on channel force-closure
6770                 let mut nodes = create_network(3);
6771                 create_announced_chan_between_nodes(&nodes, 0, 1);
6772                 create_announced_chan_between_nodes(&nodes, 1, 2);
6773
6774                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
6775
6776                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6777
6778                 let mut payment_event = {
6779                         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6780                         check_added_monitors!(nodes[0], 1);
6781
6782                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6783                         assert_eq!(events.len(), 1);
6784                         SendEvent::from_event(events.remove(0))
6785                 };
6786
6787                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6788                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6789
6790                 let events_1 = nodes[1].node.get_and_clear_pending_events();
6791                 assert_eq!(events_1.len(), 1);
6792                 match events_1[0] {
6793                         Event::PendingHTLCsForwardable { .. } => { },
6794                         _ => panic!("Unexpected event"),
6795                 };
6796
6797                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
6798                 nodes[1].node.process_pending_htlc_forwards();
6799
6800                 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6801                 assert_eq!(events_2.len(), 1);
6802                 payment_event = SendEvent::from_event(events_2.remove(0));
6803                 assert_eq!(payment_event.msgs.len(), 1);
6804
6805                 check_added_monitors!(nodes[1], 1);
6806                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6807                 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
6808                 check_added_monitors!(nodes[2], 1);
6809                 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6810
6811                 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
6812                 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
6813                 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
6814
6815                 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
6816                 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6817                 assert_eq!(events_3.len(), 1);
6818                 match events_3[0] {
6819                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6820                                 assert_eq!(flags & 0b10, 0b10);
6821                         },
6822                         _ => panic!("Unexpected event"),
6823                 }
6824
6825                 let tx = {
6826                         let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6827                         // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
6828                         // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
6829                         // back to nodes[1] upon timeout otherwise.
6830                         assert_eq!(node_txn.len(), 1);
6831                         node_txn.remove(0)
6832                 };
6833
6834                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6835                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6836
6837                 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6838                 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
6839                 assert_eq!(events_4.len(), 1);
6840                 match events_4[0] {
6841                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6842                                 assert_eq!(flags & 0b10, 0b10);
6843                         },
6844                         _ => panic!("Unexpected event"),
6845                 }
6846
6847                 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
6848                 {
6849                         let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
6850                         monitors.get_mut(&OutPoint::new(Sha256dHash::from(&payment_event.commitment_msg.channel_id[..]), 0)).unwrap()
6851                                 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
6852                 }
6853                 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6854                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6855                 assert_eq!(node_txn.len(), 1);
6856                 assert_eq!(node_txn[0].input.len(), 1);
6857                 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
6858                 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
6859                 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
6860
6861                 check_spends!(node_txn[0], tx);
6862         }
6863
6864         #[test]
6865         fn test_unconf_chan() {
6866                 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
6867                 let nodes = create_network(2);
6868                 create_announced_chan_between_nodes(&nodes, 0, 1);
6869
6870                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6871                 assert_eq!(channel_state.by_id.len(), 1);
6872                 assert_eq!(channel_state.short_to_id.len(), 1);
6873                 mem::drop(channel_state);
6874
6875                 let mut headers = Vec::new();
6876                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6877                 headers.push(header.clone());
6878                 for _i in 2..100 {
6879                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6880                         headers.push(header.clone());
6881                 }
6882                 while !headers.is_empty() {
6883                         nodes[0].node.block_disconnected(&headers.pop().unwrap());
6884                 }
6885                 {
6886                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6887                         assert_eq!(events.len(), 1);
6888                         match events[0] {
6889                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6890                                         assert_eq!(flags & 0b10, 0b10);
6891                                 },
6892                                 _ => panic!("Unexpected event"),
6893                         }
6894                 }
6895                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6896                 assert_eq!(channel_state.by_id.len(), 0);
6897                 assert_eq!(channel_state.short_to_id.len(), 0);
6898         }
6899
6900         macro_rules! get_chan_reestablish_msgs {
6901                 ($src_node: expr, $dst_node: expr) => {
6902                         {
6903                                 let mut res = Vec::with_capacity(1);
6904                                 for msg in $src_node.node.get_and_clear_pending_msg_events() {
6905                                         if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
6906                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6907                                                 res.push(msg.clone());
6908                                         } else {
6909                                                 panic!("Unexpected event")
6910                                         }
6911                                 }
6912                                 res
6913                         }
6914                 }
6915         }
6916
6917         macro_rules! handle_chan_reestablish_msgs {
6918                 ($src_node: expr, $dst_node: expr) => {
6919                         {
6920                                 let msg_events = $src_node.node.get_and_clear_pending_msg_events();
6921                                 let mut idx = 0;
6922                                 let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
6923                                         idx += 1;
6924                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6925                                         Some(msg.clone())
6926                                 } else {
6927                                         None
6928                                 };
6929
6930                                 let mut revoke_and_ack = None;
6931                                 let mut commitment_update = None;
6932                                 let order = if let Some(ev) = msg_events.get(idx) {
6933                                         idx += 1;
6934                                         match ev {
6935                                                 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6936                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6937                                                         revoke_and_ack = Some(msg.clone());
6938                                                         RAACommitmentOrder::RevokeAndACKFirst
6939                                                 },
6940                                                 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6941                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6942                                                         commitment_update = Some(updates.clone());
6943                                                         RAACommitmentOrder::CommitmentFirst
6944                                                 },
6945                                                 _ => panic!("Unexpected event"),
6946                                         }
6947                                 } else {
6948                                         RAACommitmentOrder::CommitmentFirst
6949                                 };
6950
6951                                 if let Some(ev) = msg_events.get(idx) {
6952                                         match ev {
6953                                                 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6954                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6955                                                         assert!(revoke_and_ack.is_none());
6956                                                         revoke_and_ack = Some(msg.clone());
6957                                                 },
6958                                                 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6959                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6960                                                         assert!(commitment_update.is_none());
6961                                                         commitment_update = Some(updates.clone());
6962                                                 },
6963                                                 _ => panic!("Unexpected event"),
6964                                         }
6965                                 }
6966
6967                                 (funding_locked, revoke_and_ack, commitment_update, order)
6968                         }
6969                 }
6970         }
6971
6972         /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
6973         /// for claims/fails they are separated out.
6974         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)) {
6975                 node_a.node.peer_connected(&node_b.node.get_our_node_id());
6976                 let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
6977                 node_b.node.peer_connected(&node_a.node.get_our_node_id());
6978                 let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
6979
6980                 if send_funding_locked.0 {
6981                         // If a expects a funding_locked, it better not think it has received a revoke_and_ack
6982                         // from b
6983                         for reestablish in reestablish_1.iter() {
6984                                 assert_eq!(reestablish.next_remote_commitment_number, 0);
6985                         }
6986                 }
6987                 if send_funding_locked.1 {
6988                         // If b expects a funding_locked, it better not think it has received a revoke_and_ack
6989                         // from a
6990                         for reestablish in reestablish_2.iter() {
6991                                 assert_eq!(reestablish.next_remote_commitment_number, 0);
6992                         }
6993                 }
6994                 if send_funding_locked.0 || send_funding_locked.1 {
6995                         // If we expect any funding_locked's, both sides better have set
6996                         // next_local_commitment_number to 1
6997                         for reestablish in reestablish_1.iter() {
6998                                 assert_eq!(reestablish.next_local_commitment_number, 1);
6999                         }
7000                         for reestablish in reestablish_2.iter() {
7001                                 assert_eq!(reestablish.next_local_commitment_number, 1);
7002                         }
7003                 }
7004
7005                 let mut resp_1 = Vec::new();
7006                 for msg in reestablish_1 {
7007                         node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg).unwrap();
7008                         resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
7009                 }
7010                 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
7011                         check_added_monitors!(node_b, 1);
7012                 } else {
7013                         check_added_monitors!(node_b, 0);
7014                 }
7015
7016                 let mut resp_2 = Vec::new();
7017                 for msg in reestablish_2 {
7018                         node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg).unwrap();
7019                         resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
7020                 }
7021                 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
7022                         check_added_monitors!(node_a, 1);
7023                 } else {
7024                         check_added_monitors!(node_a, 0);
7025                 }
7026
7027                 // We dont yet support both needing updates, as that would require a different commitment dance:
7028                 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
7029                         (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
7030
7031                 for chan_msgs in resp_1.drain(..) {
7032                         if send_funding_locked.0 {
7033                                 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
7034                                 let announcement_event = node_a.node.get_and_clear_pending_msg_events();
7035                                 if !announcement_event.is_empty() {
7036                                         assert_eq!(announcement_event.len(), 1);
7037                                         if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
7038                                                 //TODO: Test announcement_sigs re-sending
7039                                         } else { panic!("Unexpected event!"); }
7040                                 }
7041                         } else {
7042                                 assert!(chan_msgs.0.is_none());
7043                         }
7044                         if pending_raa.0 {
7045                                 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
7046                                 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
7047                                 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
7048                                 check_added_monitors!(node_a, 1);
7049                         } else {
7050                                 assert!(chan_msgs.1.is_none());
7051                         }
7052                         if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
7053                                 let commitment_update = chan_msgs.2.unwrap();
7054                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
7055                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
7056                                 } else {
7057                                         assert!(commitment_update.update_add_htlcs.is_empty());
7058                                 }
7059                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
7060                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
7061                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
7062                                 for update_add in commitment_update.update_add_htlcs {
7063                                         node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add).unwrap();
7064                                 }
7065                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
7066                                         node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill).unwrap();
7067                                 }
7068                                 for update_fail in commitment_update.update_fail_htlcs {
7069                                         node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail).unwrap();
7070                                 }
7071
7072                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
7073                                         commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
7074                                 } else {
7075                                         node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
7076                                         check_added_monitors!(node_a, 1);
7077                                         let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
7078                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
7079                                         node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7080                                         assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
7081                                         check_added_monitors!(node_b, 1);
7082                                 }
7083                         } else {
7084                                 assert!(chan_msgs.2.is_none());
7085                         }
7086                 }
7087
7088                 for chan_msgs in resp_2.drain(..) {
7089                         if send_funding_locked.1 {
7090                                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
7091                                 let announcement_event = node_b.node.get_and_clear_pending_msg_events();
7092                                 if !announcement_event.is_empty() {
7093                                         assert_eq!(announcement_event.len(), 1);
7094                                         if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
7095                                                 //TODO: Test announcement_sigs re-sending
7096                                         } else { panic!("Unexpected event!"); }
7097                                 }
7098                         } else {
7099                                 assert!(chan_msgs.0.is_none());
7100                         }
7101                         if pending_raa.1 {
7102                                 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
7103                                 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
7104                                 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
7105                                 check_added_monitors!(node_b, 1);
7106                         } else {
7107                                 assert!(chan_msgs.1.is_none());
7108                         }
7109                         if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
7110                                 let commitment_update = chan_msgs.2.unwrap();
7111                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
7112                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
7113                                 }
7114                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
7115                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
7116                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
7117                                 for update_add in commitment_update.update_add_htlcs {
7118                                         node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add).unwrap();
7119                                 }
7120                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
7121                                         node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill).unwrap();
7122                                 }
7123                                 for update_fail in commitment_update.update_fail_htlcs {
7124                                         node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail).unwrap();
7125                                 }
7126
7127                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
7128                                         commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
7129                                 } else {
7130                                         node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
7131                                         check_added_monitors!(node_b, 1);
7132                                         let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
7133                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
7134                                         node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7135                                         assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
7136                                         check_added_monitors!(node_a, 1);
7137                                 }
7138                         } else {
7139                                 assert!(chan_msgs.2.is_none());
7140                         }
7141                 }
7142         }
7143
7144         #[test]
7145         fn test_simple_peer_disconnect() {
7146                 // Test that we can reconnect when there are no lost messages
7147                 let nodes = create_network(3);
7148                 create_announced_chan_between_nodes(&nodes, 0, 1);
7149                 create_announced_chan_between_nodes(&nodes, 1, 2);
7150
7151                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7152                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7153                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7154
7155                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7156                 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7157                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
7158                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
7159
7160                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7161                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7162                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7163
7164                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7165                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7166                 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7167                 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7168
7169                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7170                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7171
7172                 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3);
7173                 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
7174
7175                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
7176                 {
7177                         let events = nodes[0].node.get_and_clear_pending_events();
7178                         assert_eq!(events.len(), 2);
7179                         match events[0] {
7180                                 Event::PaymentSent { payment_preimage } => {
7181                                         assert_eq!(payment_preimage, payment_preimage_3);
7182                                 },
7183                                 _ => panic!("Unexpected event"),
7184                         }
7185                         match events[1] {
7186                                 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
7187                                         assert_eq!(payment_hash, payment_hash_5);
7188                                         assert!(rejected_by_dest);
7189                                 },
7190                                 _ => panic!("Unexpected event"),
7191                         }
7192                 }
7193
7194                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
7195                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
7196         }
7197
7198         fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
7199                 // Test that we can reconnect when in-flight HTLC updates get dropped
7200                 let mut nodes = create_network(2);
7201                 if messages_delivered == 0 {
7202                         create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
7203                         // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
7204                 } else {
7205                         create_announced_chan_between_nodes(&nodes, 0, 1);
7206                 }
7207
7208                 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();
7209                 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7210
7211                 let payment_event = {
7212                         nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
7213                         check_added_monitors!(nodes[0], 1);
7214
7215                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7216                         assert_eq!(events.len(), 1);
7217                         SendEvent::from_event(events.remove(0))
7218                 };
7219                 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
7220
7221                 if messages_delivered < 2 {
7222                         // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
7223                 } else {
7224                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7225                         if messages_delivered >= 3 {
7226                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7227                                 check_added_monitors!(nodes[1], 1);
7228                                 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7229
7230                                 if messages_delivered >= 4 {
7231                                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7232                                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7233                                         check_added_monitors!(nodes[0], 1);
7234
7235                                         if messages_delivered >= 5 {
7236                                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
7237                                                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7238                                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7239                                                 check_added_monitors!(nodes[0], 1);
7240
7241                                                 if messages_delivered >= 6 {
7242                                                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7243                                                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7244                                                         check_added_monitors!(nodes[1], 1);
7245                                                 }
7246                                         }
7247                                 }
7248                         }
7249                 }
7250
7251                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7252                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7253                 if messages_delivered < 3 {
7254                         // Even if the funding_locked messages get exchanged, as long as nothing further was
7255                         // received on either side, both sides will need to resend them.
7256                         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
7257                 } else if messages_delivered == 3 {
7258                         // nodes[0] still wants its RAA + commitment_signed
7259                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
7260                 } else if messages_delivered == 4 {
7261                         // nodes[0] still wants its commitment_signed
7262                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
7263                 } else if messages_delivered == 5 {
7264                         // nodes[1] still wants its final RAA
7265                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
7266                 } else if messages_delivered == 6 {
7267                         // Everything was delivered...
7268                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7269                 }
7270
7271                 let events_1 = nodes[1].node.get_and_clear_pending_events();
7272                 assert_eq!(events_1.len(), 1);
7273                 match events_1[0] {
7274                         Event::PendingHTLCsForwardable { .. } => { },
7275                         _ => panic!("Unexpected event"),
7276                 };
7277
7278                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7279                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7280                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7281
7282                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7283                 nodes[1].node.process_pending_htlc_forwards();
7284
7285                 let events_2 = nodes[1].node.get_and_clear_pending_events();
7286                 assert_eq!(events_2.len(), 1);
7287                 match events_2[0] {
7288                         Event::PaymentReceived { ref payment_hash, amt } => {
7289                                 assert_eq!(payment_hash_1, *payment_hash);
7290                                 assert_eq!(amt, 1000000);
7291                         },
7292                         _ => panic!("Unexpected event"),
7293                 }
7294
7295                 nodes[1].node.claim_funds(payment_preimage_1);
7296                 check_added_monitors!(nodes[1], 1);
7297
7298                 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
7299                 assert_eq!(events_3.len(), 1);
7300                 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
7301                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
7302                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7303                                 assert!(updates.update_add_htlcs.is_empty());
7304                                 assert!(updates.update_fail_htlcs.is_empty());
7305                                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
7306                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
7307                                 assert!(updates.update_fee.is_none());
7308                                 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
7309                         },
7310                         _ => panic!("Unexpected event"),
7311                 };
7312
7313                 if messages_delivered >= 1 {
7314                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc).unwrap();
7315
7316                         let events_4 = nodes[0].node.get_and_clear_pending_events();
7317                         assert_eq!(events_4.len(), 1);
7318                         match events_4[0] {
7319                                 Event::PaymentSent { ref payment_preimage } => {
7320                                         assert_eq!(payment_preimage_1, *payment_preimage);
7321                                 },
7322                                 _ => panic!("Unexpected event"),
7323                         }
7324
7325                         if messages_delivered >= 2 {
7326                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
7327                                 check_added_monitors!(nodes[0], 1);
7328                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7329
7330                                 if messages_delivered >= 3 {
7331                                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7332                                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7333                                         check_added_monitors!(nodes[1], 1);
7334
7335                                         if messages_delivered >= 4 {
7336                                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
7337                                                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7338                                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7339                                                 check_added_monitors!(nodes[1], 1);
7340
7341                                                 if messages_delivered >= 5 {
7342                                                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7343                                                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7344                                                         check_added_monitors!(nodes[0], 1);
7345                                                 }
7346                                         }
7347                                 }
7348                         }
7349                 }
7350
7351                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7352                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7353                 if messages_delivered < 2 {
7354                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
7355                         //TODO: Deduplicate PaymentSent events, then enable this if:
7356                         //if messages_delivered < 1 {
7357                                 let events_4 = nodes[0].node.get_and_clear_pending_events();
7358                                 assert_eq!(events_4.len(), 1);
7359                                 match events_4[0] {
7360                                         Event::PaymentSent { ref payment_preimage } => {
7361                                                 assert_eq!(payment_preimage_1, *payment_preimage);
7362                                         },
7363                                         _ => panic!("Unexpected event"),
7364                                 }
7365                         //}
7366                 } else if messages_delivered == 2 {
7367                         // nodes[0] still wants its RAA + commitment_signed
7368                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
7369                 } else if messages_delivered == 3 {
7370                         // nodes[0] still wants its commitment_signed
7371                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
7372                 } else if messages_delivered == 4 {
7373                         // nodes[1] still wants its final RAA
7374                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
7375                 } else if messages_delivered == 5 {
7376                         // Everything was delivered...
7377                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7378                 }
7379
7380                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7381                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7382                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7383
7384                 // Channel should still work fine...
7385                 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
7386                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7387         }
7388
7389         #[test]
7390         fn test_drop_messages_peer_disconnect_a() {
7391                 do_test_drop_messages_peer_disconnect(0);
7392                 do_test_drop_messages_peer_disconnect(1);
7393                 do_test_drop_messages_peer_disconnect(2);
7394                 do_test_drop_messages_peer_disconnect(3);
7395         }
7396
7397         #[test]
7398         fn test_drop_messages_peer_disconnect_b() {
7399                 do_test_drop_messages_peer_disconnect(4);
7400                 do_test_drop_messages_peer_disconnect(5);
7401                 do_test_drop_messages_peer_disconnect(6);
7402         }
7403
7404         #[test]
7405         fn test_funding_peer_disconnect() {
7406                 // Test that we can lock in our funding tx while disconnected
7407                 let nodes = create_network(2);
7408                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
7409
7410                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7411                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7412
7413                 confirm_transaction(&nodes[0].chain_monitor, &tx, tx.version);
7414                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7415                 assert_eq!(events_1.len(), 1);
7416                 match events_1[0] {
7417                         MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7418                                 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7419                         },
7420                         _ => panic!("Unexpected event"),
7421                 }
7422
7423                 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7424
7425                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7426                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7427
7428                 confirm_transaction(&nodes[1].chain_monitor, &tx, tx.version);
7429                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7430                 assert_eq!(events_2.len(), 2);
7431                 match events_2[0] {
7432                         MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7433                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7434                         },
7435                         _ => panic!("Unexpected event"),
7436                 }
7437                 match events_2[1] {
7438                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ } => {
7439                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7440                         },
7441                         _ => panic!("Unexpected event"),
7442                 }
7443
7444                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7445
7446                 // TODO: We shouldn't need to manually pass list_usable_chanels here once we support
7447                 // rebroadcasting announcement_signatures upon reconnect.
7448
7449                 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();
7450                 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
7451                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
7452         }
7453
7454         #[test]
7455         fn test_drop_messages_peer_disconnect_dual_htlc() {
7456                 // Test that we can handle reconnecting when both sides of a channel have pending
7457                 // commitment_updates when we disconnect.
7458                 let mut nodes = create_network(2);
7459                 create_announced_chan_between_nodes(&nodes, 0, 1);
7460
7461                 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7462
7463                 // Now try to send a second payment which will fail to send
7464                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7465                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7466
7467                 nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
7468                 check_added_monitors!(nodes[0], 1);
7469
7470                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7471                 assert_eq!(events_1.len(), 1);
7472                 match events_1[0] {
7473                         MessageSendEvent::UpdateHTLCs { .. } => {},
7474                         _ => panic!("Unexpected event"),
7475                 }
7476
7477                 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7478                 check_added_monitors!(nodes[1], 1);
7479
7480                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7481                 assert_eq!(events_2.len(), 1);
7482                 match events_2[0] {
7483                         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 } } => {
7484                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7485                                 assert!(update_add_htlcs.is_empty());
7486                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7487                                 assert!(update_fail_htlcs.is_empty());
7488                                 assert!(update_fail_malformed_htlcs.is_empty());
7489                                 assert!(update_fee.is_none());
7490
7491                                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7492                                 let events_3 = nodes[0].node.get_and_clear_pending_events();
7493                                 assert_eq!(events_3.len(), 1);
7494                                 match events_3[0] {
7495                                         Event::PaymentSent { ref payment_preimage } => {
7496                                                 assert_eq!(*payment_preimage, payment_preimage_1);
7497                                         },
7498                                         _ => panic!("Unexpected event"),
7499                                 }
7500
7501                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
7502                                 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7503                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7504                                 check_added_monitors!(nodes[0], 1);
7505                         },
7506                         _ => panic!("Unexpected event"),
7507                 }
7508
7509                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7510                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7511
7512                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7513                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7514                 assert_eq!(reestablish_1.len(), 1);
7515                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7516                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7517                 assert_eq!(reestablish_2.len(), 1);
7518
7519                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7520                 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7521                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7522                 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7523
7524                 assert!(as_resp.0.is_none());
7525                 assert!(bs_resp.0.is_none());
7526
7527                 assert!(bs_resp.1.is_none());
7528                 assert!(bs_resp.2.is_none());
7529
7530                 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7531
7532                 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
7533                 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
7534                 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7535                 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7536                 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
7537                 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();
7538                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7539                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7540                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7541                 check_added_monitors!(nodes[1], 1);
7542
7543                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap();
7544                 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7545                 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
7546                 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
7547                 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
7548                 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
7549                 assert!(bs_second_commitment_signed.update_fee.is_none());
7550                 check_added_monitors!(nodes[1], 1);
7551
7552                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7553                 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7554                 assert!(as_commitment_signed.update_add_htlcs.is_empty());
7555                 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
7556                 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
7557                 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
7558                 assert!(as_commitment_signed.update_fee.is_none());
7559                 check_added_monitors!(nodes[0], 1);
7560
7561                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
7562                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7563                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7564                 check_added_monitors!(nodes[0], 1);
7565
7566                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
7567                 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7568                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7569                 check_added_monitors!(nodes[1], 1);
7570
7571                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7572                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7573                 check_added_monitors!(nodes[1], 1);
7574
7575                 let events_4 = nodes[1].node.get_and_clear_pending_events();
7576                 assert_eq!(events_4.len(), 1);
7577                 match events_4[0] {
7578                         Event::PendingHTLCsForwardable { .. } => { },
7579                         _ => panic!("Unexpected event"),
7580                 };
7581
7582                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7583                 nodes[1].node.process_pending_htlc_forwards();
7584
7585                 let events_5 = nodes[1].node.get_and_clear_pending_events();
7586                 assert_eq!(events_5.len(), 1);
7587                 match events_5[0] {
7588                         Event::PaymentReceived { ref payment_hash, amt: _ } => {
7589                                 assert_eq!(payment_hash_2, *payment_hash);
7590                         },
7591                         _ => panic!("Unexpected event"),
7592                 }
7593
7594                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
7595                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7596                 check_added_monitors!(nodes[0], 1);
7597
7598                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7599         }
7600
7601         #[test]
7602         fn test_simple_monitor_permanent_update_fail() {
7603                 // Test that we handle a simple permanent monitor update failure
7604                 let mut nodes = create_network(2);
7605                 create_announced_chan_between_nodes(&nodes, 0, 1);
7606
7607                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7608                 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7609
7610                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7611                 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route, payment_hash_1) {} else { panic!(); }
7612                 check_added_monitors!(nodes[0], 1);
7613
7614                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7615                 assert_eq!(events_1.len(), 2);
7616                 match events_1[0] {
7617                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7618                         _ => panic!("Unexpected event"),
7619                 };
7620                 match events_1[1] {
7621                         MessageSendEvent::HandleError { node_id, .. } => assert_eq!(node_id, nodes[1].node.get_our_node_id()),
7622                         _ => panic!("Unexpected event"),
7623                 };
7624
7625                 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7626                 // PaymentFailed event
7627
7628                 assert_eq!(nodes[0].node.list_channels().len(), 0);
7629         }
7630
7631         fn do_test_simple_monitor_temporary_update_fail(disconnect: bool) {
7632                 // Test that we can recover from a simple temporary monitor update failure optionally with
7633                 // a disconnect in between
7634                 let mut nodes = create_network(2);
7635                 create_announced_chan_between_nodes(&nodes, 0, 1);
7636
7637                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7638                 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7639
7640                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7641                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_1) {} else { panic!(); }
7642                 check_added_monitors!(nodes[0], 1);
7643
7644                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7645                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7646                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7647
7648                 if disconnect {
7649                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7650                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7651                         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7652                 }
7653
7654                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7655                 nodes[0].node.test_restore_channel_monitor();
7656                 check_added_monitors!(nodes[0], 1);
7657
7658                 let mut events_2 = nodes[0].node.get_and_clear_pending_msg_events();
7659                 assert_eq!(events_2.len(), 1);
7660                 let payment_event = SendEvent::from_event(events_2.pop().unwrap());
7661                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7662                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7663                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7664
7665                 expect_pending_htlcs_forwardable!(nodes[1]);
7666
7667                 let events_3 = nodes[1].node.get_and_clear_pending_events();
7668                 assert_eq!(events_3.len(), 1);
7669                 match events_3[0] {
7670                         Event::PaymentReceived { ref payment_hash, amt } => {
7671                                 assert_eq!(payment_hash_1, *payment_hash);
7672                                 assert_eq!(amt, 1000000);
7673                         },
7674                         _ => panic!("Unexpected event"),
7675                 }
7676
7677                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_1);
7678
7679                 // Now set it to failed again...
7680                 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7681                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7682                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route, payment_hash_2) {} else { panic!(); }
7683                 check_added_monitors!(nodes[0], 1);
7684
7685                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7686                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7687                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7688
7689                 if disconnect {
7690                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7691                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7692                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7693                 }
7694
7695                 // ...and make sure we can force-close a TemporaryFailure channel with a PermanentFailure
7696                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7697                 nodes[0].node.test_restore_channel_monitor();
7698                 check_added_monitors!(nodes[0], 1);
7699
7700                 let events_5 = nodes[0].node.get_and_clear_pending_msg_events();
7701                 assert_eq!(events_5.len(), 1);
7702                 match events_5[0] {
7703                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7704                         _ => panic!("Unexpected event"),
7705                 }
7706
7707                 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7708                 // PaymentFailed event
7709
7710                 assert_eq!(nodes[0].node.list_channels().len(), 0);
7711         }
7712
7713         #[test]
7714         fn test_simple_monitor_temporary_update_fail() {
7715                 do_test_simple_monitor_temporary_update_fail(false);
7716                 do_test_simple_monitor_temporary_update_fail(true);
7717         }
7718
7719         fn do_test_monitor_temporary_update_fail(disconnect_count: usize) {
7720                 let disconnect_flags = 8 | 16;
7721
7722                 // Test that we can recover from a temporary monitor update failure with some in-flight
7723                 // HTLCs going on at the same time potentially with some disconnection thrown in.
7724                 // * First we route a payment, then get a temporary monitor update failure when trying to
7725                 //   route a second payment. We then claim the first payment.
7726                 // * If disconnect_count is set, we will disconnect at this point (which is likely as
7727                 //   TemporaryFailure likely indicates net disconnect which resulted in failing to update
7728                 //   the ChannelMonitor on a watchtower).
7729                 // * If !(disconnect_count & 16) we deliver a update_fulfill_htlc/CS for the first payment
7730                 //   immediately, otherwise we wait sconnect and deliver them via the reconnect
7731                 //   channel_reestablish processing (ie disconnect_count & 16 makes no sense if
7732                 //   disconnect_count & !disconnect_flags is 0).
7733                 // * We then update the channel monitor, reconnecting if disconnect_count is set and walk
7734                 //   through message sending, potentially disconnect/reconnecting multiple times based on
7735                 //   disconnect_count, to get the update_fulfill_htlc through.
7736                 // * We then walk through more message exchanges to get the original update_add_htlc
7737                 //   through, swapping message ordering based on disconnect_count & 8 and optionally
7738                 //   disconnect/reconnecting based on disconnect_count.
7739                 let mut nodes = create_network(2);
7740                 create_announced_chan_between_nodes(&nodes, 0, 1);
7741
7742                 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7743
7744                 // Now try to send a second payment which will fail to send
7745                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7746                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7747
7748                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7749                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_2) {} else { panic!(); }
7750                 check_added_monitors!(nodes[0], 1);
7751
7752                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7753                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7754                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7755
7756                 // Claim the previous payment, which will result in a update_fulfill_htlc/CS from nodes[1]
7757                 // but nodes[0] won't respond since it is frozen.
7758                 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7759                 check_added_monitors!(nodes[1], 1);
7760                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7761                 assert_eq!(events_2.len(), 1);
7762                 let (bs_initial_fulfill, bs_initial_commitment_signed) = match events_2[0] {
7763                         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 } } => {
7764                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7765                                 assert!(update_add_htlcs.is_empty());
7766                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7767                                 assert!(update_fail_htlcs.is_empty());
7768                                 assert!(update_fail_malformed_htlcs.is_empty());
7769                                 assert!(update_fee.is_none());
7770
7771                                 if (disconnect_count & 16) == 0 {
7772                                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7773                                         let events_3 = nodes[0].node.get_and_clear_pending_events();
7774                                         assert_eq!(events_3.len(), 1);
7775                                         match events_3[0] {
7776                                                 Event::PaymentSent { ref payment_preimage } => {
7777                                                         assert_eq!(*payment_preimage, payment_preimage_1);
7778                                                 },
7779                                                 _ => panic!("Unexpected event"),
7780                                         }
7781
7782                                         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) {
7783                                                 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
7784                                         } else { panic!(); }
7785                                 }
7786
7787                                 (update_fulfill_htlcs[0].clone(), commitment_signed.clone())
7788                         },
7789                         _ => panic!("Unexpected event"),
7790                 };
7791
7792                 if disconnect_count & !disconnect_flags > 0 {
7793                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7794                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7795                 }
7796
7797                 // Now fix monitor updating...
7798                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7799                 nodes[0].node.test_restore_channel_monitor();
7800                 check_added_monitors!(nodes[0], 1);
7801
7802                 macro_rules! disconnect_reconnect_peers { () => { {
7803                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7804                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7805
7806                         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7807                         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7808                         assert_eq!(reestablish_1.len(), 1);
7809                         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7810                         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7811                         assert_eq!(reestablish_2.len(), 1);
7812
7813                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7814                         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7815                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7816                         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7817
7818                         assert!(as_resp.0.is_none());
7819                         assert!(bs_resp.0.is_none());
7820
7821                         (reestablish_1, reestablish_2, as_resp, bs_resp)
7822                 } } }
7823
7824                 let (payment_event, initial_revoke_and_ack) = if disconnect_count & !disconnect_flags > 0 {
7825                         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7826                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7827
7828                         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7829                         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7830                         assert_eq!(reestablish_1.len(), 1);
7831                         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7832                         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7833                         assert_eq!(reestablish_2.len(), 1);
7834
7835                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7836                         check_added_monitors!(nodes[0], 0);
7837                         let mut as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7838                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7839                         check_added_monitors!(nodes[1], 0);
7840                         let mut bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7841
7842                         assert!(as_resp.0.is_none());
7843                         assert!(bs_resp.0.is_none());
7844
7845                         assert!(bs_resp.1.is_none());
7846                         if (disconnect_count & 16) == 0 {
7847                                 assert!(bs_resp.2.is_none());
7848
7849                                 assert!(as_resp.1.is_some());
7850                                 assert!(as_resp.2.is_some());
7851                                 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7852                         } else {
7853                                 assert!(bs_resp.2.as_ref().unwrap().update_add_htlcs.is_empty());
7854                                 assert!(bs_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7855                                 assert!(bs_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7856                                 assert!(bs_resp.2.as_ref().unwrap().update_fee.is_none());
7857                                 assert!(bs_resp.2.as_ref().unwrap().update_fulfill_htlcs == vec![bs_initial_fulfill]);
7858                                 assert!(bs_resp.2.as_ref().unwrap().commitment_signed == bs_initial_commitment_signed);
7859
7860                                 assert!(as_resp.1.is_none());
7861
7862                                 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();
7863                                 let events_3 = nodes[0].node.get_and_clear_pending_events();
7864                                 assert_eq!(events_3.len(), 1);
7865                                 match events_3[0] {
7866                                         Event::PaymentSent { ref payment_preimage } => {
7867                                                 assert_eq!(*payment_preimage, payment_preimage_1);
7868                                         },
7869                                         _ => panic!("Unexpected event"),
7870                                 }
7871
7872                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7873                                 let as_resp_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7874                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7875                                 check_added_monitors!(nodes[0], 1);
7876
7877                                 as_resp.1 = Some(as_resp_raa);
7878                                 bs_resp.2 = None;
7879                         }
7880
7881                         if disconnect_count & !disconnect_flags > 1 {
7882                                 let (second_reestablish_1, second_reestablish_2, second_as_resp, second_bs_resp) = disconnect_reconnect_peers!();
7883
7884                                 if (disconnect_count & 16) == 0 {
7885                                         assert!(reestablish_1 == second_reestablish_1);
7886                                         assert!(reestablish_2 == second_reestablish_2);
7887                                 }
7888                                 assert!(as_resp == second_as_resp);
7889                                 assert!(bs_resp == second_bs_resp);
7890                         }
7891
7892                         (SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), as_resp.2.unwrap()), as_resp.1.unwrap())
7893                 } else {
7894                         let mut events_4 = nodes[0].node.get_and_clear_pending_msg_events();
7895                         assert_eq!(events_4.len(), 2);
7896                         (SendEvent::from_event(events_4.remove(0)), match events_4[0] {
7897                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
7898                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7899                                         msg.clone()
7900                                 },
7901                                 _ => panic!("Unexpected event"),
7902                         })
7903                 };
7904
7905                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7906
7907                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7908                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7909                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7910                 // nodes[1] is awaiting an RAA from nodes[0] still so get_event_msg's assert(len == 1) passes
7911                 check_added_monitors!(nodes[1], 1);
7912
7913                 if disconnect_count & !disconnect_flags > 2 {
7914                         let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7915
7916                         assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7917                         assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7918
7919                         assert!(as_resp.2.is_none());
7920                         assert!(bs_resp.2.is_none());
7921                 }
7922
7923                 let as_commitment_update;
7924                 let bs_second_commitment_update;
7925
7926                 macro_rules! handle_bs_raa { () => {
7927                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7928                         as_commitment_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7929                         assert!(as_commitment_update.update_add_htlcs.is_empty());
7930                         assert!(as_commitment_update.update_fulfill_htlcs.is_empty());
7931                         assert!(as_commitment_update.update_fail_htlcs.is_empty());
7932                         assert!(as_commitment_update.update_fail_malformed_htlcs.is_empty());
7933                         assert!(as_commitment_update.update_fee.is_none());
7934                         check_added_monitors!(nodes[0], 1);
7935                 } }
7936
7937                 macro_rules! handle_initial_raa { () => {
7938                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &initial_revoke_and_ack).unwrap();
7939                         bs_second_commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7940                         assert!(bs_second_commitment_update.update_add_htlcs.is_empty());
7941                         assert!(bs_second_commitment_update.update_fulfill_htlcs.is_empty());
7942                         assert!(bs_second_commitment_update.update_fail_htlcs.is_empty());
7943                         assert!(bs_second_commitment_update.update_fail_malformed_htlcs.is_empty());
7944                         assert!(bs_second_commitment_update.update_fee.is_none());
7945                         check_added_monitors!(nodes[1], 1);
7946                 } }
7947
7948                 if (disconnect_count & 8) == 0 {
7949                         handle_bs_raa!();
7950
7951                         if disconnect_count & !disconnect_flags > 3 {
7952                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7953
7954                                 assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7955                                 assert!(bs_resp.1.is_none());
7956
7957                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7958                                 assert!(bs_resp.2.is_none());
7959
7960                                 assert!(as_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7961                         }
7962
7963                         handle_initial_raa!();
7964
7965                         if disconnect_count & !disconnect_flags > 4 {
7966                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7967
7968                                 assert!(as_resp.1.is_none());
7969                                 assert!(bs_resp.1.is_none());
7970
7971                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7972                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7973                         }
7974                 } else {
7975                         handle_initial_raa!();
7976
7977                         if disconnect_count & !disconnect_flags > 3 {
7978                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7979
7980                                 assert!(as_resp.1.is_none());
7981                                 assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7982
7983                                 assert!(as_resp.2.is_none());
7984                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7985
7986                                 assert!(bs_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7987                         }
7988
7989                         handle_bs_raa!();
7990
7991                         if disconnect_count & !disconnect_flags > 4 {
7992                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7993
7994                                 assert!(as_resp.1.is_none());
7995                                 assert!(bs_resp.1.is_none());
7996
7997                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7998                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7999                         }
8000                 }
8001
8002                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_update.commitment_signed).unwrap();
8003                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8004                 // No commitment_signed so get_event_msg's assert(len == 1) passes
8005                 check_added_monitors!(nodes[0], 1);
8006
8007                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_update.commitment_signed).unwrap();
8008                 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
8009                 // No commitment_signed so get_event_msg's assert(len == 1) passes
8010                 check_added_monitors!(nodes[1], 1);
8011
8012                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
8013                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8014                 check_added_monitors!(nodes[1], 1);
8015
8016                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
8017                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8018                 check_added_monitors!(nodes[0], 1);
8019
8020                 expect_pending_htlcs_forwardable!(nodes[1]);
8021
8022                 let events_5 = nodes[1].node.get_and_clear_pending_events();
8023                 assert_eq!(events_5.len(), 1);
8024                 match events_5[0] {
8025                         Event::PaymentReceived { ref payment_hash, amt } => {
8026                                 assert_eq!(payment_hash_2, *payment_hash);
8027                                 assert_eq!(amt, 1000000);
8028                         },
8029                         _ => panic!("Unexpected event"),
8030                 }
8031
8032                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
8033         }
8034
8035         #[test]
8036         fn test_monitor_temporary_update_fail_a() {
8037                 do_test_monitor_temporary_update_fail(0);
8038                 do_test_monitor_temporary_update_fail(1);
8039                 do_test_monitor_temporary_update_fail(2);
8040                 do_test_monitor_temporary_update_fail(3);
8041                 do_test_monitor_temporary_update_fail(4);
8042                 do_test_monitor_temporary_update_fail(5);
8043         }
8044
8045         #[test]
8046         fn test_monitor_temporary_update_fail_b() {
8047                 do_test_monitor_temporary_update_fail(2 | 8);
8048                 do_test_monitor_temporary_update_fail(3 | 8);
8049                 do_test_monitor_temporary_update_fail(4 | 8);
8050                 do_test_monitor_temporary_update_fail(5 | 8);
8051         }
8052
8053         #[test]
8054         fn test_monitor_temporary_update_fail_c() {
8055                 do_test_monitor_temporary_update_fail(1 | 16);
8056                 do_test_monitor_temporary_update_fail(2 | 16);
8057                 do_test_monitor_temporary_update_fail(3 | 16);
8058                 do_test_monitor_temporary_update_fail(2 | 8 | 16);
8059                 do_test_monitor_temporary_update_fail(3 | 8 | 16);
8060         }
8061
8062         #[test]
8063         fn test_monitor_update_fail_cs() {
8064                 // Tests handling of a monitor update failure when processing an incoming commitment_signed
8065                 let mut nodes = create_network(2);
8066                 create_announced_chan_between_nodes(&nodes, 0, 1);
8067
8068                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8069                 let (payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
8070                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
8071                 check_added_monitors!(nodes[0], 1);
8072
8073                 let send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8074                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8075
8076                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8077                 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() {
8078                         assert_eq!(err, "Failed to update ChannelMonitor");
8079                 } else { panic!(); }
8080                 check_added_monitors!(nodes[1], 1);
8081                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8082
8083                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8084                 nodes[1].node.test_restore_channel_monitor();
8085                 check_added_monitors!(nodes[1], 1);
8086                 let responses = nodes[1].node.get_and_clear_pending_msg_events();
8087                 assert_eq!(responses.len(), 2);
8088
8089                 match responses[0] {
8090                         MessageSendEvent::SendRevokeAndACK { ref msg, ref node_id } => {
8091                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8092                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &msg).unwrap();
8093                                 check_added_monitors!(nodes[0], 1);
8094                         },
8095                         _ => panic!("Unexpected event"),
8096                 }
8097                 match responses[1] {
8098                         MessageSendEvent::UpdateHTLCs { ref updates, ref node_id } => {
8099                                 assert!(updates.update_add_htlcs.is_empty());
8100                                 assert!(updates.update_fulfill_htlcs.is_empty());
8101                                 assert!(updates.update_fail_htlcs.is_empty());
8102                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8103                                 assert!(updates.update_fee.is_none());
8104                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8105
8106                                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8107                                 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() {
8108                                         assert_eq!(err, "Failed to update ChannelMonitor");
8109                                 } else { panic!(); }
8110                                 check_added_monitors!(nodes[0], 1);
8111                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8112                         },
8113                         _ => panic!("Unexpected event"),
8114                 }
8115
8116                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
8117                 nodes[0].node.test_restore_channel_monitor();
8118                 check_added_monitors!(nodes[0], 1);
8119
8120                 let final_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8121                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &final_raa).unwrap();
8122                 check_added_monitors!(nodes[1], 1);
8123
8124                 let mut events = nodes[1].node.get_and_clear_pending_events();
8125                 assert_eq!(events.len(), 1);
8126                 match events[0] {
8127                         Event::PendingHTLCsForwardable { .. } => { },
8128                         _ => panic!("Unexpected event"),
8129                 };
8130                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8131                 nodes[1].node.process_pending_htlc_forwards();
8132
8133                 events = nodes[1].node.get_and_clear_pending_events();
8134                 assert_eq!(events.len(), 1);
8135                 match events[0] {
8136                         Event::PaymentReceived { payment_hash, amt } => {
8137                                 assert_eq!(payment_hash, our_payment_hash);
8138                                 assert_eq!(amt, 1000000);
8139                         },
8140                         _ => panic!("Unexpected event"),
8141                 };
8142
8143                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
8144         }
8145
8146         fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) {
8147                 // Tests handling of a monitor update failure when processing an incoming RAA
8148                 let mut nodes = create_network(3);
8149                 create_announced_chan_between_nodes(&nodes, 0, 1);
8150                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
8151
8152                 // Rebalance a bit so that we can send backwards from 2 to 1.
8153                 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 5000000);
8154
8155                 // Route a first payment that we'll fail backwards
8156                 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
8157
8158                 // Fail the payment backwards, failing the monitor update on nodes[1]'s receipt of the RAA
8159                 assert!(nodes[2].node.fail_htlc_backwards(&payment_hash_1, PaymentFailReason::PreimageUnknown));
8160                 check_added_monitors!(nodes[2], 1);
8161
8162                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8163                 assert!(updates.update_add_htlcs.is_empty());
8164                 assert!(updates.update_fulfill_htlcs.is_empty());
8165                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8166                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8167                 assert!(updates.update_fee.is_none());
8168                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
8169
8170                 let bs_revoke_and_ack = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
8171                 check_added_monitors!(nodes[0], 0);
8172
8173                 // While the second channel is AwaitingRAA, forward a second payment to get it into the
8174                 // holding cell.
8175                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
8176                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8177                 nodes[0].node.send_payment(route, payment_hash_2).unwrap();
8178                 check_added_monitors!(nodes[0], 1);
8179
8180                 let mut send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8181                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8182                 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false);
8183
8184                 let events_1 = nodes[1].node.get_and_clear_pending_events();
8185                 assert_eq!(events_1.len(), 1);
8186                 match events_1[0] {
8187                         Event::PendingHTLCsForwardable { .. } => { },
8188                         _ => panic!("Unexpected event"),
8189                 };
8190
8191                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8192                 nodes[1].node.process_pending_htlc_forwards();
8193                 check_added_monitors!(nodes[1], 0);
8194                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8195
8196                 // Now fail monitor updating.
8197                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8198                 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() {
8199                         assert_eq!(err, "Failed to update ChannelMonitor");
8200                 } else { panic!(); }
8201                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8202                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8203                 check_added_monitors!(nodes[1], 1);
8204
8205                 // Attempt to forward a third payment but fail due to the second channel being unavailable
8206                 // for forwarding.
8207
8208                 let (_, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
8209                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8210                 nodes[0].node.send_payment(route, payment_hash_3).unwrap();
8211                 check_added_monitors!(nodes[0], 1);
8212
8213                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(()); // We succeed in updating the monitor for the first channel
8214                 send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8215                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8216                 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
8217                 check_added_monitors!(nodes[1], 0);
8218
8219                 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8220                 assert_eq!(events_2.len(), 1);
8221                 match events_2.remove(0) {
8222                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
8223                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8224                                 assert!(updates.update_fulfill_htlcs.is_empty());
8225                                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8226                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8227                                 assert!(updates.update_add_htlcs.is_empty());
8228                                 assert!(updates.update_fee.is_none());
8229
8230                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
8231                                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
8232
8233                                 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
8234                                 assert_eq!(msg_events.len(), 1);
8235                                 match msg_events[0] {
8236                                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
8237                                                 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
8238                                                 assert_eq!(msg.contents.flags & 2, 2); // temp disabled
8239                                         },
8240                                         _ => panic!("Unexpected event"),
8241                                 }
8242
8243                                 let events = nodes[0].node.get_and_clear_pending_events();
8244                                 assert_eq!(events.len(), 1);
8245                                 if let Event::PaymentFailed { payment_hash, rejected_by_dest, .. } = events[0] {
8246                                         assert_eq!(payment_hash, payment_hash_3);
8247                                         assert!(!rejected_by_dest);
8248                                 } else { panic!("Unexpected event!"); }
8249                         },
8250                         _ => panic!("Unexpected event type!"),
8251                 };
8252
8253                 let (payment_preimage_4, payment_hash_4) = if test_ignore_second_cs {
8254                         // Try to route another payment backwards from 2 to make sure 1 holds off on responding
8255                         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[0]);
8256                         let route = nodes[2].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8257                         nodes[2].node.send_payment(route, payment_hash_4).unwrap();
8258                         check_added_monitors!(nodes[2], 1);
8259
8260                         send_event = SendEvent::from_event(nodes[2].node.get_and_clear_pending_msg_events().remove(0));
8261                         nodes[1].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8262                         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) {
8263                                 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
8264                         } else { panic!(); }
8265                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8266                         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8267                         (Some(payment_preimage_4), Some(payment_hash_4))
8268                 } else { (None, None) };
8269
8270                 // Restore monitor updating, ensuring we immediately get a fail-back update and a
8271                 // update_add update.
8272                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8273                 nodes[1].node.test_restore_channel_monitor();
8274                 check_added_monitors!(nodes[1], 2);
8275
8276                 let mut events_3 = nodes[1].node.get_and_clear_pending_msg_events();
8277                 if test_ignore_second_cs {
8278                         assert_eq!(events_3.len(), 3);
8279                 } else {
8280                         assert_eq!(events_3.len(), 2);
8281                 }
8282
8283                 // Note that the ordering of the events for different nodes is non-prescriptive, though the
8284                 // ordering of the two events that both go to nodes[2] have to stay in the same order.
8285                 let messages_a = match events_3.pop().unwrap() {
8286                         MessageSendEvent::UpdateHTLCs { node_id, mut updates } => {
8287                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8288                                 assert!(updates.update_fulfill_htlcs.is_empty());
8289                                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8290                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8291                                 assert!(updates.update_add_htlcs.is_empty());
8292                                 assert!(updates.update_fee.is_none());
8293                                 (updates.update_fail_htlcs.remove(0), updates.commitment_signed)
8294                         },
8295                         _ => panic!("Unexpected event type!"),
8296                 };
8297                 let raa = if test_ignore_second_cs {
8298                         match events_3.remove(1) {
8299                                 MessageSendEvent::SendRevokeAndACK { node_id, msg } => {
8300                                         assert_eq!(node_id, nodes[2].node.get_our_node_id());
8301                                         Some(msg.clone())
8302                                 },
8303                                 _ => panic!("Unexpected event"),
8304                         }
8305                 } else { None };
8306                 let send_event_b = SendEvent::from_event(events_3.remove(0));
8307                 assert_eq!(send_event_b.node_id, nodes[2].node.get_our_node_id());
8308
8309                 // Now deliver the new messages...
8310
8311                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &messages_a.0).unwrap();
8312                 commitment_signed_dance!(nodes[0], nodes[1], messages_a.1, false);
8313                 let events_4 = nodes[0].node.get_and_clear_pending_events();
8314                 assert_eq!(events_4.len(), 1);
8315                 if let Event::PaymentFailed { payment_hash, rejected_by_dest, .. } = events_4[0] {
8316                         assert_eq!(payment_hash, payment_hash_1);
8317                         assert!(rejected_by_dest);
8318                 } else { panic!("Unexpected event!"); }
8319
8320                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event_b.msgs[0]).unwrap();
8321                 if test_ignore_second_cs {
8322                         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event_b.commitment_msg).unwrap();
8323                         check_added_monitors!(nodes[2], 1);
8324                         let bs_revoke_and_ack = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8325                         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa.unwrap()).unwrap();
8326                         check_added_monitors!(nodes[2], 1);
8327                         let bs_cs = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8328                         assert!(bs_cs.update_add_htlcs.is_empty());
8329                         assert!(bs_cs.update_fail_htlcs.is_empty());
8330                         assert!(bs_cs.update_fail_malformed_htlcs.is_empty());
8331                         assert!(bs_cs.update_fulfill_htlcs.is_empty());
8332                         assert!(bs_cs.update_fee.is_none());
8333
8334                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
8335                         check_added_monitors!(nodes[1], 1);
8336                         let as_cs = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
8337                         assert!(as_cs.update_add_htlcs.is_empty());
8338                         assert!(as_cs.update_fail_htlcs.is_empty());
8339                         assert!(as_cs.update_fail_malformed_htlcs.is_empty());
8340                         assert!(as_cs.update_fulfill_htlcs.is_empty());
8341                         assert!(as_cs.update_fee.is_none());
8342
8343                         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_cs.commitment_signed).unwrap();
8344                         check_added_monitors!(nodes[1], 1);
8345                         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
8346
8347                         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_cs.commitment_signed).unwrap();
8348                         check_added_monitors!(nodes[2], 1);
8349                         let bs_second_raa = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8350
8351                         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
8352                         check_added_monitors!(nodes[2], 1);
8353                         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
8354
8355                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_second_raa).unwrap();
8356                         check_added_monitors!(nodes[1], 1);
8357                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8358                 } else {
8359                         commitment_signed_dance!(nodes[2], nodes[1], send_event_b.commitment_msg, false);
8360                 }
8361
8362                 let events_5 = nodes[2].node.get_and_clear_pending_events();
8363                 assert_eq!(events_5.len(), 1);
8364                 match events_5[0] {
8365                         Event::PendingHTLCsForwardable { .. } => { },
8366                         _ => panic!("Unexpected event"),
8367                 };
8368
8369                 nodes[2].node.channel_state.lock().unwrap().next_forward = Instant::now();
8370                 nodes[2].node.process_pending_htlc_forwards();
8371
8372                 let events_6 = nodes[2].node.get_and_clear_pending_events();
8373                 assert_eq!(events_6.len(), 1);
8374                 match events_6[0] {
8375                         Event::PaymentReceived { payment_hash, .. } => { assert_eq!(payment_hash, payment_hash_2); },
8376                         _ => panic!("Unexpected event"),
8377                 };
8378
8379                 if test_ignore_second_cs {
8380                         let events_7 = nodes[1].node.get_and_clear_pending_events();
8381                         assert_eq!(events_7.len(), 1);
8382                         match events_7[0] {
8383                                 Event::PendingHTLCsForwardable { .. } => { },
8384                                 _ => panic!("Unexpected event"),
8385                         };
8386
8387                         nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8388                         nodes[1].node.process_pending_htlc_forwards();
8389                         check_added_monitors!(nodes[1], 1);
8390
8391                         send_event = SendEvent::from_node(&nodes[1]);
8392                         assert_eq!(send_event.node_id, nodes[0].node.get_our_node_id());
8393                         assert_eq!(send_event.msgs.len(), 1);
8394                         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8395                         commitment_signed_dance!(nodes[0], nodes[1], send_event.commitment_msg, false);
8396
8397                         let events_8 = nodes[0].node.get_and_clear_pending_events();
8398                         assert_eq!(events_8.len(), 1);
8399                         match events_8[0] {
8400                                 Event::PendingHTLCsForwardable { .. } => { },
8401                                 _ => panic!("Unexpected event"),
8402                         };
8403
8404                         nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
8405                         nodes[0].node.process_pending_htlc_forwards();
8406
8407                         let events_9 = nodes[0].node.get_and_clear_pending_events();
8408                         assert_eq!(events_9.len(), 1);
8409                         match events_9[0] {
8410                                 Event::PaymentReceived { payment_hash, .. } => assert_eq!(payment_hash, payment_hash_4.unwrap()),
8411                                 _ => panic!("Unexpected event"),
8412                         };
8413                         claim_payment(&nodes[2], &[&nodes[1], &nodes[0]], payment_preimage_4.unwrap());
8414                 }
8415
8416                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
8417         }
8418
8419         #[test]
8420         fn test_monitor_update_fail_raa() {
8421                 do_test_monitor_update_fail_raa(false);
8422                 do_test_monitor_update_fail_raa(true);
8423         }
8424
8425         #[test]
8426         fn test_monitor_update_fail_reestablish() {
8427                 // Simple test for message retransmission after monitor update failure on
8428                 // channel_reestablish generating a monitor update (which comes from freeing holding cell
8429                 // HTLCs).
8430                 let mut nodes = create_network(3);
8431                 create_announced_chan_between_nodes(&nodes, 0, 1);
8432                 create_announced_chan_between_nodes(&nodes, 1, 2);
8433
8434                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
8435
8436                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8437                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8438
8439                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
8440                 check_added_monitors!(nodes[2], 1);
8441                 let mut updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8442                 assert!(updates.update_add_htlcs.is_empty());
8443                 assert!(updates.update_fail_htlcs.is_empty());
8444                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8445                 assert!(updates.update_fee.is_none());
8446                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8447                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8448                 check_added_monitors!(nodes[1], 1);
8449                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8450                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
8451
8452                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8453                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8454                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8455
8456                 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
8457                 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8458
8459                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
8460
8461                 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() {
8462                         assert_eq!(err, "Failed to update ChannelMonitor");
8463                 } else { panic!(); }
8464                 check_added_monitors!(nodes[1], 1);
8465
8466                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8467                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8468
8469                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8470                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8471
8472                 assert!(as_reestablish == get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()));
8473                 assert!(bs_reestablish == get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id()));
8474
8475                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
8476
8477                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish).unwrap();
8478                 check_added_monitors!(nodes[1], 0);
8479                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8480
8481                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8482                 nodes[1].node.test_restore_channel_monitor();
8483                 check_added_monitors!(nodes[1], 1);
8484
8485                 updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8486                 assert!(updates.update_add_htlcs.is_empty());
8487                 assert!(updates.update_fail_htlcs.is_empty());
8488                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8489                 assert!(updates.update_fee.is_none());
8490                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8491                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8492                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
8493
8494                 let events = nodes[0].node.get_and_clear_pending_events();
8495                 assert_eq!(events.len(), 1);
8496                 match events[0] {
8497                         Event::PaymentSent { payment_preimage, .. } => assert_eq!(payment_preimage, our_payment_preimage),
8498                         _ => panic!("Unexpected event"),
8499                 }
8500         }
8501
8502         #[test]
8503         fn test_invalid_channel_announcement() {
8504                 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
8505                 let secp_ctx = Secp256k1::new();
8506                 let nodes = create_network(2);
8507
8508                 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1]);
8509
8510                 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8511                 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
8512                 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
8513                 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
8514
8515                 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 } );
8516
8517                 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
8518                 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
8519
8520                 let as_network_key = nodes[0].node.get_our_node_id();
8521                 let bs_network_key = nodes[1].node.get_our_node_id();
8522
8523                 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
8524
8525                 let mut chan_announcement;
8526
8527                 macro_rules! dummy_unsigned_msg {
8528                         () => {
8529                                 msgs::UnsignedChannelAnnouncement {
8530                                         features: msgs::GlobalFeatures::new(),
8531                                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
8532                                         short_channel_id: as_chan.get_short_channel_id().unwrap(),
8533                                         node_id_1: if were_node_one { as_network_key } else { bs_network_key },
8534                                         node_id_2: if were_node_one { bs_network_key } else { as_network_key },
8535                                         bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
8536                                         bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
8537                                         excess_data: Vec::new(),
8538                                 };
8539                         }
8540                 }
8541
8542                 macro_rules! sign_msg {
8543                         ($unsigned_msg: expr) => {
8544                                 let msghash = Message::from_slice(&Sha256dHash::from_data(&$unsigned_msg.encode()[..])[..]).unwrap();
8545                                 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
8546                                 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
8547                                 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].node.our_network_key);
8548                                 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].node.our_network_key);
8549                                 chan_announcement = msgs::ChannelAnnouncement {
8550                                         node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
8551                                         node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
8552                                         bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
8553                                         bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
8554                                         contents: $unsigned_msg
8555                                 }
8556                         }
8557                 }
8558
8559                 let unsigned_msg = dummy_unsigned_msg!();
8560                 sign_msg!(unsigned_msg);
8561                 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
8562                 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 } );
8563
8564                 // Configured with Network::Testnet
8565                 let mut unsigned_msg = dummy_unsigned_msg!();
8566                 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
8567                 sign_msg!(unsigned_msg);
8568                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
8569
8570                 let mut unsigned_msg = dummy_unsigned_msg!();
8571                 unsigned_msg.chain_hash = Sha256dHash::from_data(&[1,2,3,4,5,6,7,8,9]);
8572                 sign_msg!(unsigned_msg);
8573                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
8574         }
8575
8576         struct VecWriter(Vec<u8>);
8577         impl Writer for VecWriter {
8578                 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
8579                         self.0.extend_from_slice(buf);
8580                         Ok(())
8581                 }
8582                 fn size_hint(&mut self, size: usize) {
8583                         self.0.reserve_exact(size);
8584                 }
8585         }
8586
8587         #[test]
8588         fn test_no_txn_manager_serialize_deserialize() {
8589                 let mut nodes = create_network(2);
8590
8591                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
8592
8593                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8594
8595                 let nodes_0_serialized = nodes[0].node.encode();
8596                 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8597                 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8598
8599                 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())));
8600                 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8601                 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8602                 assert!(chan_0_monitor_read.is_empty());
8603
8604                 let mut nodes_0_read = &nodes_0_serialized[..];
8605                 let config = UserConfig::new();
8606                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8607                 let (_, nodes_0_deserialized) = {
8608                         let mut channel_monitors = HashMap::new();
8609                         channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8610                         <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8611                                 default_config: config,
8612                                 keys_manager,
8613                                 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8614                                 monitor: nodes[0].chan_monitor.clone(),
8615                                 chain_monitor: nodes[0].chain_monitor.clone(),
8616                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8617                                 logger: Arc::new(test_utils::TestLogger::new()),
8618                                 channel_monitors: &channel_monitors,
8619                         }).unwrap()
8620                 };
8621                 assert!(nodes_0_read.is_empty());
8622
8623                 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8624                 nodes[0].node = Arc::new(nodes_0_deserialized);
8625                 let nodes_0_as_listener: Arc<ChainListener> = nodes[0].node.clone();
8626                 nodes[0].chain_monitor.register_listener(Arc::downgrade(&nodes_0_as_listener));
8627                 assert_eq!(nodes[0].node.list_channels().len(), 1);
8628                 check_added_monitors!(nodes[0], 1);
8629
8630                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8631                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
8632                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8633                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
8634
8635                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
8636                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8637                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
8638                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8639
8640                 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8641                 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8642                 for node in nodes.iter() {
8643                         assert!(node.router.handle_channel_announcement(&announcement).unwrap());
8644                         node.router.handle_channel_update(&as_update).unwrap();
8645                         node.router.handle_channel_update(&bs_update).unwrap();
8646                 }
8647
8648                 send_payment(&nodes[0], &[&nodes[1]], 1000000);
8649         }
8650
8651         #[test]
8652         fn test_simple_manager_serialize_deserialize() {
8653                 let mut nodes = create_network(2);
8654                 create_announced_chan_between_nodes(&nodes, 0, 1);
8655
8656                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8657                 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8658
8659                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8660
8661                 let nodes_0_serialized = nodes[0].node.encode();
8662                 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8663                 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8664
8665                 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())));
8666                 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8667                 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8668                 assert!(chan_0_monitor_read.is_empty());
8669
8670                 let mut nodes_0_read = &nodes_0_serialized[..];
8671                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8672                 let (_, nodes_0_deserialized) = {
8673                         let mut channel_monitors = HashMap::new();
8674                         channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8675                         <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8676                                 default_config: UserConfig::new(),
8677                                 keys_manager,
8678                                 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8679                                 monitor: nodes[0].chan_monitor.clone(),
8680                                 chain_monitor: nodes[0].chain_monitor.clone(),
8681                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8682                                 logger: Arc::new(test_utils::TestLogger::new()),
8683                                 channel_monitors: &channel_monitors,
8684                         }).unwrap()
8685                 };
8686                 assert!(nodes_0_read.is_empty());
8687
8688                 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8689                 nodes[0].node = Arc::new(nodes_0_deserialized);
8690                 check_added_monitors!(nodes[0], 1);
8691
8692                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8693
8694                 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
8695                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
8696         }
8697
8698         #[test]
8699         fn test_manager_serialize_deserialize_inconsistent_monitor() {
8700                 // Test deserializing a ChannelManager with a out-of-date ChannelMonitor
8701                 let mut nodes = create_network(4);
8702                 create_announced_chan_between_nodes(&nodes, 0, 1);
8703                 create_announced_chan_between_nodes(&nodes, 2, 0);
8704                 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3);
8705
8706                 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
8707
8708                 // Serialize the ChannelManager here, but the monitor we keep up-to-date
8709                 let nodes_0_serialized = nodes[0].node.encode();
8710
8711                 route_payment(&nodes[0], &[&nodes[3]], 1000000);
8712                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8713                 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8714                 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8715
8716                 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
8717                 // nodes[3])
8718                 let mut node_0_monitors_serialized = Vec::new();
8719                 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
8720                         let mut writer = VecWriter(Vec::new());
8721                         monitor.1.write_for_disk(&mut writer).unwrap();
8722                         node_0_monitors_serialized.push(writer.0);
8723                 }
8724
8725                 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())));
8726                 let mut node_0_monitors = Vec::new();
8727                 for serialized in node_0_monitors_serialized.iter() {
8728                         let mut read = &serialized[..];
8729                         let (_, monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
8730                         assert!(read.is_empty());
8731                         node_0_monitors.push(monitor);
8732                 }
8733
8734                 let mut nodes_0_read = &nodes_0_serialized[..];
8735                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8736                 let (_, nodes_0_deserialized) = <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8737                         default_config: UserConfig::new(),
8738                         keys_manager,
8739                         fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8740                         monitor: nodes[0].chan_monitor.clone(),
8741                         chain_monitor: nodes[0].chain_monitor.clone(),
8742                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8743                         logger: Arc::new(test_utils::TestLogger::new()),
8744                         channel_monitors: &node_0_monitors.iter().map(|monitor| { (monitor.get_funding_txo().unwrap(), monitor) }).collect(),
8745                 }).unwrap();
8746                 assert!(nodes_0_read.is_empty());
8747
8748                 { // Channel close should result in a commitment tx and an HTLC tx
8749                         let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8750                         assert_eq!(txn.len(), 2);
8751                         assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
8752                         assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
8753                 }
8754
8755                 for monitor in node_0_monitors.drain(..) {
8756                         assert!(nodes[0].chan_monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor).is_ok());
8757                         check_added_monitors!(nodes[0], 1);
8758                 }
8759                 nodes[0].node = Arc::new(nodes_0_deserialized);
8760
8761                 // nodes[1] and nodes[2] have no lost state with nodes[0]...
8762                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8763                 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8764                 //... and we can even still claim the payment!
8765                 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
8766
8767                 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id());
8768                 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8769                 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id());
8770                 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) {
8771                         assert_eq!(msg.channel_id, channel_id);
8772                 } else { panic!("Unexpected result"); }
8773         }
8774
8775         macro_rules! check_spendable_outputs {
8776                 ($node: expr, $der_idx: expr) => {
8777                         {
8778                                 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
8779                                 let mut txn = Vec::new();
8780                                 for event in events {
8781                                         match event {
8782                                                 Event::SpendableOutputs { ref outputs } => {
8783                                                         for outp in outputs {
8784                                                                 match *outp {
8785                                                                         SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
8786                                                                                 let input = TxIn {
8787                                                                                         previous_output: outpoint.clone(),
8788                                                                                         script_sig: Script::new(),
8789                                                                                         sequence: 0,
8790                                                                                         witness: Vec::new(),
8791                                                                                 };
8792                                                                                 let outp = TxOut {
8793                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8794                                                                                         value: output.value,
8795                                                                                 };
8796                                                                                 let mut spend_tx = Transaction {
8797                                                                                         version: 2,
8798                                                                                         lock_time: 0,
8799                                                                                         input: vec![input],
8800                                                                                         output: vec![outp],
8801                                                                                 };
8802                                                                                 let secp_ctx = Secp256k1::new();
8803                                                                                 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
8804                                                                                 let witness_script = Address::p2pkh(&remotepubkey, Network::Testnet).script_pubkey();
8805                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8806                                                                                 let remotesig = secp_ctx.sign(&sighash, key);
8807                                                                                 spend_tx.input[0].witness.push(remotesig.serialize_der(&secp_ctx).to_vec());
8808                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8809                                                                                 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
8810                                                                                 txn.push(spend_tx);
8811                                                                         },
8812                                                                         SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
8813                                                                                 let input = TxIn {
8814                                                                                         previous_output: outpoint.clone(),
8815                                                                                         script_sig: Script::new(),
8816                                                                                         sequence: *to_self_delay as u32,
8817                                                                                         witness: Vec::new(),
8818                                                                                 };
8819                                                                                 let outp = TxOut {
8820                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8821                                                                                         value: output.value,
8822                                                                                 };
8823                                                                                 let mut spend_tx = Transaction {
8824                                                                                         version: 2,
8825                                                                                         lock_time: 0,
8826                                                                                         input: vec![input],
8827                                                                                         output: vec![outp],
8828                                                                                 };
8829                                                                                 let secp_ctx = Secp256k1::new();
8830                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
8831                                                                                 let local_delaysig = secp_ctx.sign(&sighash, key);
8832                                                                                 spend_tx.input[0].witness.push(local_delaysig.serialize_der(&secp_ctx).to_vec());
8833                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8834                                                                                 spend_tx.input[0].witness.push(vec!(0));
8835                                                                                 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
8836                                                                                 txn.push(spend_tx);
8837                                                                         },
8838                                                                         SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
8839                                                                                 let secp_ctx = Secp256k1::new();
8840                                                                                 let input = TxIn {
8841                                                                                         previous_output: outpoint.clone(),
8842                                                                                         script_sig: Script::new(),
8843                                                                                         sequence: 0,
8844                                                                                         witness: Vec::new(),
8845                                                                                 };
8846                                                                                 let outp = TxOut {
8847                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8848                                                                                         value: output.value,
8849                                                                                 };
8850                                                                                 let mut spend_tx = Transaction {
8851                                                                                         version: 2,
8852                                                                                         lock_time: 0,
8853                                                                                         input: vec![input],
8854                                                                                         output: vec![outp.clone()],
8855                                                                                 };
8856                                                                                 let secret = {
8857                                                                                         match ExtendedPrivKey::new_master(&secp_ctx, Network::Testnet, &$node.node_seed) {
8858                                                                                                 Ok(master_key) => {
8859                                                                                                         match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx)) {
8860                                                                                                                 Ok(key) => key,
8861                                                                                                                 Err(_) => panic!("Your RNG is busted"),
8862                                                                                                         }
8863                                                                                                 }
8864                                                                                                 Err(_) => panic!("Your rng is busted"),
8865                                                                                         }
8866                                                                                 };
8867                                                                                 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
8868                                                                                 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
8869                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8870                                                                                 let sig = secp_ctx.sign(&sighash, &secret.secret_key);
8871                                                                                 spend_tx.input[0].witness.push(sig.serialize_der(&secp_ctx).to_vec());
8872                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8873                                                                                 spend_tx.input[0].witness.push(pubkey.serialize().to_vec());
8874                                                                                 txn.push(spend_tx);
8875                                                                         },
8876                                                                 }
8877                                                         }
8878                                                 },
8879                                                 _ => panic!("Unexpected event"),
8880                                         };
8881                                 }
8882                                 txn
8883                         }
8884                 }
8885         }
8886
8887         #[test]
8888         fn test_claim_sizeable_push_msat() {
8889                 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
8890                 let nodes = create_network(2);
8891
8892                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8893                 nodes[1].node.force_close_channel(&chan.2);
8894                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8895                 match events[0] {
8896                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8897                         _ => panic!("Unexpected event"),
8898                 }
8899                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8900                 assert_eq!(node_txn.len(), 1);
8901                 check_spends!(node_txn[0], chan.3.clone());
8902                 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
8903
8904                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8905                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8906                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8907                 assert_eq!(spend_txn.len(), 1);
8908                 check_spends!(spend_txn[0], node_txn[0].clone());
8909         }
8910
8911         #[test]
8912         fn test_claim_on_remote_sizeable_push_msat() {
8913                 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8914                 // to_remote output is encumbered by a P2WPKH
8915
8916                 let nodes = create_network(2);
8917
8918                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8919                 nodes[0].node.force_close_channel(&chan.2);
8920                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8921                 match events[0] {
8922                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8923                         _ => panic!("Unexpected event"),
8924                 }
8925                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8926                 assert_eq!(node_txn.len(), 1);
8927                 check_spends!(node_txn[0], chan.3.clone());
8928                 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
8929
8930                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8931                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8932                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8933                 match events[0] {
8934                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8935                         _ => panic!("Unexpected event"),
8936                 }
8937                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8938                 assert_eq!(spend_txn.len(), 2);
8939                 assert_eq!(spend_txn[0], spend_txn[1]);
8940                 check_spends!(spend_txn[0], node_txn[0].clone());
8941         }
8942
8943         #[test]
8944         fn test_claim_on_remote_revoked_sizeable_push_msat() {
8945                 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8946                 // to_remote output is encumbered by a P2WPKH
8947
8948                 let nodes = create_network(2);
8949
8950                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
8951                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8952                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
8953                 assert_eq!(revoked_local_txn[0].input.len(), 1);
8954                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8955
8956                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8957                 let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8958                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
8959                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8960                 match events[0] {
8961                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8962                         _ => panic!("Unexpected event"),
8963                 }
8964                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8965                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8966                 assert_eq!(spend_txn.len(), 4);
8967                 assert_eq!(spend_txn[0], spend_txn[2]); // to_remote output on revoked remote commitment_tx
8968                 check_spends!(spend_txn[0], revoked_local_txn[0].clone());
8969                 assert_eq!(spend_txn[1], spend_txn[3]); // to_local output on local commitment tx
8970                 check_spends!(spend_txn[1], node_txn[0].clone());
8971         }
8972
8973         #[test]
8974         fn test_static_spendable_outputs_preimage_tx() {
8975                 let nodes = create_network(2);
8976
8977                 // Create some initial channels
8978                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8979
8980                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8981
8982                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8983                 assert_eq!(commitment_tx[0].input.len(), 1);
8984                 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
8985
8986                 // Settle A's commitment tx on B's chain
8987                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8988                 assert!(nodes[1].node.claim_funds(payment_preimage));
8989                 check_added_monitors!(nodes[1], 1);
8990                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
8991                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8992                 match events[0] {
8993                         MessageSendEvent::UpdateHTLCs { .. } => {},
8994                         _ => panic!("Unexpected event"),
8995                 }
8996                 match events[1] {
8997                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8998                         _ => panic!("Unexepected event"),
8999                 }
9000
9001                 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
9002                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 1 (local commitment tx), ChannelMonitor: 2 (1 preimage tx) * 2 (block-rescan)
9003                 check_spends!(node_txn[0], commitment_tx[0].clone());
9004                 assert_eq!(node_txn[0], node_txn[2]);
9005                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9006                 check_spends!(node_txn[1], chan_1.3.clone());
9007
9008                 let spend_txn = check_spendable_outputs!(nodes[1], 1); // , 0, 0, 1, 1);
9009                 assert_eq!(spend_txn.len(), 2);
9010                 assert_eq!(spend_txn[0], spend_txn[1]);
9011                 check_spends!(spend_txn[0], node_txn[0].clone());
9012         }
9013
9014         #[test]
9015         fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
9016                 let nodes = create_network(2);
9017
9018                 // Create some initial channels
9019                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9020
9021                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9022                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
9023                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9024                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9025
9026                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9027
9028                 let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9029                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9030                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9031                 match events[0] {
9032                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9033                         _ => panic!("Unexpected event"),
9034                 }
9035                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9036                 assert_eq!(node_txn.len(), 3);
9037                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]);
9038                 assert_eq!(node_txn[0].input.len(), 2);
9039                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
9040
9041                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9042                 assert_eq!(spend_txn.len(), 2);
9043                 assert_eq!(spend_txn[0], spend_txn[1]);
9044                 check_spends!(spend_txn[0], node_txn[0].clone());
9045         }
9046
9047         #[test]
9048         fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
9049                 let nodes = create_network(2);
9050
9051                 // Create some initial channels
9052                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9053
9054                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9055                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9056                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9057                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9058
9059                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9060
9061                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9062                 // A will generate HTLC-Timeout from revoked commitment tx
9063                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9064                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9065                 match events[0] {
9066                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9067                         _ => panic!("Unexpected event"),
9068                 }
9069                 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9070                 assert_eq!(revoked_htlc_txn.len(), 3);
9071                 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
9072                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
9073                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9074                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
9075                 check_spends!(revoked_htlc_txn[1], chan_1.3.clone());
9076
9077                 // B will generate justice tx from A's revoked commitment/HTLC tx
9078                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
9079                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9080                 match events[0] {
9081                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9082                         _ => panic!("Unexpected event"),
9083                 }
9084
9085                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9086                 assert_eq!(node_txn.len(), 4);
9087                 assert_eq!(node_txn[3].input.len(), 1);
9088                 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
9089
9090                 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
9091                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9092                 assert_eq!(spend_txn.len(), 3);
9093                 assert_eq!(spend_txn[0], spend_txn[1]);
9094                 check_spends!(spend_txn[0], node_txn[0].clone());
9095                 check_spends!(spend_txn[2], node_txn[3].clone());
9096         }
9097
9098         #[test]
9099         fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
9100                 let nodes = create_network(2);
9101
9102                 // Create some initial channels
9103                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9104
9105                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9106                 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9107                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9108                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9109
9110                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9111
9112                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9113                 // B will generate HTLC-Success from revoked commitment tx
9114                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9115                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9116                 match events[0] {
9117                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9118                         _ => panic!("Unexpected event"),
9119                 }
9120                 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9121
9122                 assert_eq!(revoked_htlc_txn.len(), 3);
9123                 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
9124                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
9125                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9126                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
9127
9128                 // A will generate justice tx from B's revoked commitment/HTLC tx
9129                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
9130                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9131                 match events[0] {
9132                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9133                         _ => panic!("Unexpected event"),
9134                 }
9135
9136                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9137                 assert_eq!(node_txn.len(), 4);
9138                 assert_eq!(node_txn[3].input.len(), 1);
9139                 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
9140
9141                 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
9142                 let spend_txn = check_spendable_outputs!(nodes[0], 1);
9143                 assert_eq!(spend_txn.len(), 5);
9144                 assert_eq!(spend_txn[0], spend_txn[2]);
9145                 assert_eq!(spend_txn[1], spend_txn[3]);
9146                 check_spends!(spend_txn[0], revoked_local_txn[0].clone()); // spending to_remote output from revoked local tx
9147                 check_spends!(spend_txn[1], node_txn[2].clone()); // spending justice tx output from revoked local tx htlc received output
9148                 check_spends!(spend_txn[4], node_txn[3].clone()); // spending justice tx output on htlc success tx
9149         }
9150
9151         #[test]
9152         fn test_onchain_to_onchain_claim() {
9153                 // Test that in case of channel closure, we detect the state of output thanks to
9154                 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
9155                 // First, have C claim an HTLC against its own latest commitment transaction.
9156                 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
9157                 // channel.
9158                 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
9159                 // gets broadcast.
9160
9161                 let nodes = create_network(3);
9162
9163                 // Create some initial channels
9164                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9165                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
9166
9167                 // Rebalance the network a bit by relaying one payment through all the channels ...
9168                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
9169                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
9170
9171                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
9172                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9173                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
9174                 check_spends!(commitment_tx[0], chan_2.3.clone());
9175                 nodes[2].node.claim_funds(payment_preimage);
9176                 check_added_monitors!(nodes[2], 1);
9177                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9178                 assert!(updates.update_add_htlcs.is_empty());
9179                 assert!(updates.update_fail_htlcs.is_empty());
9180                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
9181                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9182
9183                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
9184                 let events = nodes[2].node.get_and_clear_pending_msg_events();
9185                 assert_eq!(events.len(), 1);
9186                 match events[0] {
9187                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9188                         _ => panic!("Unexpected event"),
9189                 }
9190
9191                 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
9192                 assert_eq!(c_txn.len(), 3);
9193                 assert_eq!(c_txn[0], c_txn[2]);
9194                 assert_eq!(commitment_tx[0], c_txn[1]);
9195                 check_spends!(c_txn[1], chan_2.3.clone());
9196                 check_spends!(c_txn[2], c_txn[1].clone());
9197                 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
9198                 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9199                 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
9200                 assert_eq!(c_txn[0].lock_time, 0); // Success tx
9201
9202                 // 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
9203                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
9204                 {
9205                         let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9206                         assert_eq!(b_txn.len(), 4);
9207                         assert_eq!(b_txn[0], b_txn[3]);
9208                         check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
9209                         check_spends!(b_txn[2], b_txn[1].clone()); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
9210                         assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9211                         assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
9212                         assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
9213                         check_spends!(b_txn[0], c_txn[1].clone()); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
9214                         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9215                         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
9216                         assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
9217                         b_txn.clear();
9218                 }
9219                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
9220                 check_added_monitors!(nodes[1], 1);
9221                 match msg_events[0] {
9222                         MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
9223                         _ => panic!("Unexpected event"),
9224                 }
9225                 match msg_events[1] {
9226                         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, .. } } => {
9227                                 assert!(update_add_htlcs.is_empty());
9228                                 assert!(update_fail_htlcs.is_empty());
9229                                 assert_eq!(update_fulfill_htlcs.len(), 1);
9230                                 assert!(update_fail_malformed_htlcs.is_empty());
9231                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
9232                         },
9233                         _ => panic!("Unexpected event"),
9234                 };
9235                 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
9236                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9237                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
9238                 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9239                 assert_eq!(b_txn.len(), 3);
9240                 check_spends!(b_txn[1], chan_1.3); // Local commitment tx, issued by ChannelManager
9241                 assert_eq!(b_txn[0], b_txn[2]); // HTLC-Success tx, issued by ChannelMonitor, * 2 due to block rescan
9242                 check_spends!(b_txn[0], commitment_tx[0].clone());
9243                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9244                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
9245                 assert_eq!(b_txn[2].lock_time, 0); // Success tx
9246                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
9247                 match msg_events[0] {
9248                         MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
9249                         _ => panic!("Unexpected event"),
9250                 }
9251         }
9252
9253         #[test]
9254         fn test_duplicate_payment_hash_one_failure_one_success() {
9255                 // Topology : A --> B --> C
9256                 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
9257                 let mut nodes = create_network(3);
9258
9259                 create_announced_chan_between_nodes(&nodes, 0, 1);
9260                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
9261
9262                 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
9263                 *nodes[0].network_payment_count.borrow_mut() -= 1;
9264                 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
9265
9266                 let commitment_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
9267                 assert_eq!(commitment_txn[0].input.len(), 1);
9268                 check_spends!(commitment_txn[0], chan_2.3.clone());
9269
9270                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9271                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
9272                 let htlc_timeout_tx;
9273                 { // Extract one of the two HTLC-Timeout transaction
9274                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9275                         assert_eq!(node_txn.len(), 7);
9276                         assert_eq!(node_txn[0], node_txn[5]);
9277                         assert_eq!(node_txn[1], node_txn[6]);
9278                         check_spends!(node_txn[0], commitment_txn[0].clone());
9279                         assert_eq!(node_txn[0].input.len(), 1);
9280                         check_spends!(node_txn[1], commitment_txn[0].clone());
9281                         assert_eq!(node_txn[1].input.len(), 1);
9282                         assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
9283                         check_spends!(node_txn[2], chan_2.3.clone());
9284                         check_spends!(node_txn[3], node_txn[2].clone());
9285                         check_spends!(node_txn[4], node_txn[2].clone());
9286                         htlc_timeout_tx = node_txn[1].clone();
9287                 }
9288
9289                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9290                 match events[0] {
9291                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9292                         _ => panic!("Unexepected event"),
9293                 }
9294
9295                 nodes[2].node.claim_funds(our_payment_preimage);
9296                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
9297                 check_added_monitors!(nodes[2], 2);
9298                 let events = nodes[2].node.get_and_clear_pending_msg_events();
9299                 match events[0] {
9300                         MessageSendEvent::UpdateHTLCs { .. } => {},
9301                         _ => panic!("Unexpected event"),
9302                 }
9303                 match events[1] {
9304                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9305                         _ => panic!("Unexepected event"),
9306                 }
9307                 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9308                 assert_eq!(htlc_success_txn.len(), 5);
9309                 check_spends!(htlc_success_txn[2], chan_2.3.clone());
9310                 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
9311                 assert_eq!(htlc_success_txn[0].input.len(), 1);
9312                 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9313                 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
9314                 assert_eq!(htlc_success_txn[1].input.len(), 1);
9315                 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9316                 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
9317                 check_spends!(htlc_success_txn[0], commitment_txn[0].clone());
9318                 check_spends!(htlc_success_txn[1], commitment_txn[0].clone());
9319
9320                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
9321                 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9322                 assert!(htlc_updates.update_add_htlcs.is_empty());
9323                 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
9324                 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
9325                 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
9326                 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
9327                 check_added_monitors!(nodes[1], 1);
9328
9329                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]).unwrap();
9330                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9331                 {
9332                         commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
9333                         let events = nodes[0].node.get_and_clear_pending_msg_events();
9334                         assert_eq!(events.len(), 1);
9335                         match events[0] {
9336                                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
9337                                 },
9338                                 _ => { panic!("Unexpected event"); }
9339                         }
9340                 }
9341                 let events = nodes[0].node.get_and_clear_pending_events();
9342                 match events[0] {
9343                         Event::PaymentFailed { ref payment_hash, .. } => {
9344                                 assert_eq!(*payment_hash, duplicate_payment_hash);
9345                         }
9346                         _ => panic!("Unexpected event"),
9347                 }
9348
9349                 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
9350                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
9351                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9352                 assert!(updates.update_add_htlcs.is_empty());
9353                 assert!(updates.update_fail_htlcs.is_empty());
9354                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
9355                 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
9356                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9357                 check_added_monitors!(nodes[1], 1);
9358
9359                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
9360                 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
9361
9362                 let events = nodes[0].node.get_and_clear_pending_events();
9363                 match events[0] {
9364                         Event::PaymentSent { ref payment_preimage } => {
9365                                 assert_eq!(*payment_preimage, our_payment_preimage);
9366                         }
9367                         _ => panic!("Unexpected event"),
9368                 }
9369         }
9370
9371         #[test]
9372         fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
9373                 let nodes = create_network(2);
9374
9375                 // Create some initial channels
9376                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9377
9378                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
9379                 let local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9380                 assert_eq!(local_txn[0].input.len(), 1);
9381                 check_spends!(local_txn[0], chan_1.3.clone());
9382
9383                 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
9384                 nodes[1].node.claim_funds(payment_preimage);
9385                 check_added_monitors!(nodes[1], 1);
9386                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9387                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
9388                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9389                 match events[0] {
9390                         MessageSendEvent::UpdateHTLCs { .. } => {},
9391                         _ => panic!("Unexpected event"),
9392                 }
9393                 match events[1] {
9394                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9395                         _ => panic!("Unexepected event"),
9396                 }
9397                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9398                 assert_eq!(node_txn[0].input.len(), 1);
9399                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9400                 check_spends!(node_txn[0], local_txn[0].clone());
9401
9402                 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
9403                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9404                 assert_eq!(spend_txn.len(), 2);
9405                 check_spends!(spend_txn[0], node_txn[0].clone());
9406                 check_spends!(spend_txn[1], node_txn[2].clone());
9407         }
9408
9409         #[test]
9410         fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
9411                 let nodes = create_network(2);
9412
9413                 // Create some initial channels
9414                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9415
9416                 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
9417                 let local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9418                 assert_eq!(local_txn[0].input.len(), 1);
9419                 check_spends!(local_txn[0], chan_1.3.clone());
9420
9421                 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
9422                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9423                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
9424                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9425                 match events[0] {
9426                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9427                         _ => panic!("Unexepected event"),
9428                 }
9429                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9430                 assert_eq!(node_txn[0].input.len(), 1);
9431                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9432                 check_spends!(node_txn[0], local_txn[0].clone());
9433
9434                 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
9435                 let spend_txn = check_spendable_outputs!(nodes[0], 1);
9436                 assert_eq!(spend_txn.len(), 8);
9437                 assert_eq!(spend_txn[0], spend_txn[2]);
9438                 assert_eq!(spend_txn[0], spend_txn[4]);
9439                 assert_eq!(spend_txn[0], spend_txn[6]);
9440                 assert_eq!(spend_txn[1], spend_txn[3]);
9441                 assert_eq!(spend_txn[1], spend_txn[5]);
9442                 assert_eq!(spend_txn[1], spend_txn[7]);
9443                 check_spends!(spend_txn[0], local_txn[0].clone());
9444                 check_spends!(spend_txn[1], node_txn[0].clone());
9445         }
9446
9447         #[test]
9448         fn test_static_output_closing_tx() {
9449                 let nodes = create_network(2);
9450
9451                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
9452
9453                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
9454                 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
9455
9456                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9457                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
9458                 let spend_txn = check_spendable_outputs!(nodes[0], 2);
9459                 assert_eq!(spend_txn.len(), 1);
9460                 check_spends!(spend_txn[0], closing_tx.clone());
9461
9462                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
9463                 let spend_txn = check_spendable_outputs!(nodes[1], 2);
9464                 assert_eq!(spend_txn.len(), 1);
9465                 check_spends!(spend_txn[0], closing_tx);
9466         }
9467 }