Add additional log traces in channelmonitor/manager
[rust-lightning] / src / ln / channelmanager.rs
1 //! The top-level channel management and payment tracking stuff lives here.
2 //!
3 //! The ChannelManager is the main chunk of logic implementing the lightning protocol and is
4 //! responsible for tracking which channels are open, HTLCs are in flight and reestablishing those
5 //! upon reconnect to the relevant peer(s).
6 //!
7 //! It does not manage routing logic (see ln::router for that) nor does it manage constructing
8 //! on-chain transactions (it only monitors the chain to watch for any force-closes that might
9 //! imply it needs to fail HTLCs/payments/channels it manages).
10
11 use bitcoin::blockdata::block::BlockHeader;
12 use bitcoin::blockdata::transaction::Transaction;
13 use bitcoin::blockdata::constants::genesis_block;
14 use bitcoin::network::constants::Network;
15 use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
16
17 use secp256k1::key::{SecretKey,PublicKey};
18 use secp256k1::{Secp256k1,Message};
19 use secp256k1::ecdh::SharedSecret;
20 use secp256k1;
21
22 use chain::chaininterface::{BroadcasterInterface,ChainListener,ChainWatchInterface,FeeEstimator};
23 use chain::transaction::OutPoint;
24 use ln::channel::{Channel, ChannelError};
25 use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, ManyChannelMonitor, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS};
26 use ln::router::{Route,RouteHop};
27 use ln::msgs;
28 use ln::msgs::{ChannelMessageHandler, DecodeError, HandleError};
29 use chain::keysinterface::KeysInterface;
30 use util::config::UserConfig;
31 use util::{byte_utils, events, internal_traits, rng};
32 use util::sha2::Sha256;
33 use util::ser::{Readable, ReadableArgs, Writeable, Writer};
34 use util::chacha20poly1305rfc::ChaCha20;
35 use util::logger::Logger;
36 use util::errors::APIError;
37
38 use crypto;
39 use crypto::mac::{Mac,MacResult};
40 use crypto::hmac::Hmac;
41 use crypto::digest::Digest;
42 use crypto::symmetriccipher::SynchronousStreamCipher;
43
44 use std::{cmp, ptr, mem};
45 use std::collections::{HashMap, hash_map, HashSet};
46 use std::io::Cursor;
47 use std::sync::{Arc, Mutex, MutexGuard, RwLock};
48 use std::sync::atomic::{AtomicUsize, Ordering};
49 use std::time::{Instant,Duration};
50
51 /// We hold various information about HTLC relay in the HTLC objects in Channel itself:
52 ///
53 /// Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
54 /// forward the HTLC with information it will give back to us when it does so, or if it should Fail
55 /// the HTLC with the relevant message for the Channel to handle giving to the remote peer.
56 ///
57 /// When a Channel forwards an HTLC to its peer, it will give us back the PendingForwardHTLCInfo
58 /// which we will use to construct an outbound HTLC, with a relevant HTLCSource::PreviousHopData
59 /// filled in to indicate where it came from (which we can use to either fail-backwards or fulfill
60 /// the HTLC backwards along the relevant path).
61 /// Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
62 /// our payment, which we can use to decode errors or inform the user that the payment was sent.
63 mod channel_held_info {
64         use ln::msgs;
65         use ln::router::Route;
66         use ln::channelmanager::PaymentHash;
67         use secp256k1::key::SecretKey;
68
69         /// Stores the info we will need to send when we want to forward an HTLC onwards
70         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
71         pub struct PendingForwardHTLCInfo {
72                 pub(super) onion_packet: Option<msgs::OnionPacket>,
73                 pub(super) incoming_shared_secret: [u8; 32],
74                 pub(super) payment_hash: PaymentHash,
75                 pub(super) short_channel_id: u64,
76                 pub(super) amt_to_forward: u64,
77                 pub(super) outgoing_cltv_value: u32,
78         }
79
80         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
81         pub enum HTLCFailureMsg {
82                 Relay(msgs::UpdateFailHTLC),
83                 Malformed(msgs::UpdateFailMalformedHTLC),
84         }
85
86         /// Stores whether we can't forward an HTLC or relevant forwarding info
87         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
88         pub enum PendingHTLCStatus {
89                 Forward(PendingForwardHTLCInfo),
90                 Fail(HTLCFailureMsg),
91         }
92
93         /// Tracks the inbound corresponding to an outbound HTLC
94         #[derive(Clone, PartialEq)]
95         pub struct HTLCPreviousHopData {
96                 pub(super) short_channel_id: u64,
97                 pub(super) htlc_id: u64,
98                 pub(super) incoming_packet_shared_secret: [u8; 32],
99         }
100
101         /// Tracks the inbound corresponding to an outbound HTLC
102         #[derive(Clone, PartialEq)]
103         pub enum HTLCSource {
104                 PreviousHopData(HTLCPreviousHopData),
105                 OutboundRoute {
106                         route: Route,
107                         session_priv: SecretKey,
108                         /// Technically we can recalculate this from the route, but we cache it here to avoid
109                         /// doing a double-pass on route when we get a failure back
110                         first_hop_htlc_msat: u64,
111                 },
112         }
113         #[cfg(test)]
114         impl HTLCSource {
115                 pub fn dummy() -> Self {
116                         HTLCSource::OutboundRoute {
117                                 route: Route { hops: Vec::new() },
118                                 session_priv: SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[1; 32]).unwrap(),
119                                 first_hop_htlc_msat: 0,
120                         }
121                 }
122         }
123
124         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
125         pub(crate) enum HTLCFailReason {
126                 ErrorPacket {
127                         err: msgs::OnionErrorPacket,
128                 },
129                 Reason {
130                         failure_code: u16,
131                         data: Vec<u8>,
132                 }
133         }
134 }
135 pub(super) use self::channel_held_info::*;
136
137 /// payment_hash type, use to cross-lock hop
138 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
139 pub struct PaymentHash(pub [u8;32]);
140 /// payment_preimage type, use to route payment between hop
141 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
142 pub struct PaymentPreimage(pub [u8;32]);
143
144 type ShutdownResult = (Vec<Transaction>, Vec<(HTLCSource, PaymentHash)>);
145
146 /// Error type returned across the channel_state mutex boundary. When an Err is generated for a
147 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
148 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
149 /// channel_state lock. We then return the set of things that need to be done outside the lock in
150 /// this struct and call handle_error!() on it.
151
152 struct MsgHandleErrInternal {
153         err: msgs::HandleError,
154         shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
155 }
156 impl MsgHandleErrInternal {
157         #[inline]
158         fn send_err_msg_no_close(err: &'static str, channel_id: [u8; 32]) -> Self {
159                 Self {
160                         err: HandleError {
161                                 err,
162                                 action: Some(msgs::ErrorAction::SendErrorMessage {
163                                         msg: msgs::ErrorMessage {
164                                                 channel_id,
165                                                 data: err.to_string()
166                                         },
167                                 }),
168                         },
169                         shutdown_finish: None,
170                 }
171         }
172         #[inline]
173         fn from_no_close(err: msgs::HandleError) -> Self {
174                 Self { err, shutdown_finish: None }
175         }
176         #[inline]
177         fn from_finish_shutdown(err: &'static str, channel_id: [u8; 32], shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
178                 Self {
179                         err: HandleError {
180                                 err,
181                                 action: Some(msgs::ErrorAction::SendErrorMessage {
182                                         msg: msgs::ErrorMessage {
183                                                 channel_id,
184                                                 data: err.to_string()
185                                         },
186                                 }),
187                         },
188                         shutdown_finish: Some((shutdown_res, channel_update)),
189                 }
190         }
191         #[inline]
192         fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
193                 Self {
194                         err: match err {
195                                 ChannelError::Ignore(msg) => HandleError {
196                                         err: msg,
197                                         action: Some(msgs::ErrorAction::IgnoreError),
198                                 },
199                                 ChannelError::Close(msg) => HandleError {
200                                         err: msg,
201                                         action: Some(msgs::ErrorAction::SendErrorMessage {
202                                                 msg: msgs::ErrorMessage {
203                                                         channel_id,
204                                                         data: msg.to_string()
205                                                 },
206                                         }),
207                                 },
208                         },
209                         shutdown_finish: None,
210                 }
211         }
212 }
213
214 /// Pass to fail_htlc_backwwards to indicate the reason to fail the payment
215 /// after a PaymentReceived event.
216 #[derive(PartialEq)]
217 pub enum PaymentFailReason {
218         /// Indicate the preimage for payment_hash is not known after a PaymentReceived event
219         PreimageUnknown,
220         /// Indicate the payment amount is incorrect ( received is < expected or > 2*expected ) after a PaymentReceived event
221         AmountMismatch,
222 }
223
224 /// We hold back HTLCs we intend to relay for a random interval in the range (this, 5*this). This
225 /// provides some limited amount of privacy. Ideally this would range from somewhere like 1 second
226 /// to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly. We could
227 /// probably increase this significantly.
228 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
229
230 struct HTLCForwardInfo {
231         prev_short_channel_id: u64,
232         prev_htlc_id: u64,
233         forward_info: PendingForwardHTLCInfo,
234 }
235
236 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
237 /// be sent in the order they appear in the return value, however sometimes the order needs to be
238 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
239 /// they were originally sent). In those cases, this enum is also returned.
240 #[derive(Clone, PartialEq)]
241 pub(super) enum RAACommitmentOrder {
242         /// Send the CommitmentUpdate messages first
243         CommitmentFirst,
244         /// Send the RevokeAndACK message first
245         RevokeAndACKFirst,
246 }
247
248 struct ChannelHolder {
249         by_id: HashMap<[u8; 32], Channel>,
250         short_to_id: HashMap<u64, [u8; 32]>,
251         next_forward: Instant,
252         /// short channel id -> forward infos. Key of 0 means payments received
253         /// Note that while this is held in the same mutex as the channels themselves, no consistency
254         /// guarantees are made about there existing a channel with the short id here, nor the short
255         /// ids in the PendingForwardHTLCInfo!
256         forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
257         /// Note that while this is held in the same mutex as the channels themselves, no consistency
258         /// guarantees are made about the channels given here actually existing anymore by the time you
259         /// go to read them!
260         claimable_htlcs: HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
261         /// Messages to send to peers - pushed to in the same lock that they are generated in (except
262         /// for broadcast messages, where ordering isn't as strict).
263         pending_msg_events: Vec<events::MessageSendEvent>,
264 }
265 struct MutChannelHolder<'a> {
266         by_id: &'a mut HashMap<[u8; 32], Channel>,
267         short_to_id: &'a mut HashMap<u64, [u8; 32]>,
268         next_forward: &'a mut Instant,
269         forward_htlcs: &'a mut HashMap<u64, Vec<HTLCForwardInfo>>,
270         claimable_htlcs: &'a mut HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
271         pending_msg_events: &'a mut Vec<events::MessageSendEvent>,
272 }
273 impl ChannelHolder {
274         fn borrow_parts(&mut self) -> MutChannelHolder {
275                 MutChannelHolder {
276                         by_id: &mut self.by_id,
277                         short_to_id: &mut self.short_to_id,
278                         next_forward: &mut self.next_forward,
279                         forward_htlcs: &mut self.forward_htlcs,
280                         claimable_htlcs: &mut self.claimable_htlcs,
281                         pending_msg_events: &mut self.pending_msg_events,
282                 }
283         }
284 }
285
286 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
287 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
288
289 /// Manager which keeps track of a number of channels and sends messages to the appropriate
290 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
291 ///
292 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
293 /// to individual Channels.
294 ///
295 /// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
296 /// all peers during write/read (though does not modify this instance, only the instance being
297 /// serialized). This will result in any channels which have not yet exchanged funding_created (ie
298 /// called funding_transaction_generated for outbound channels).
299 ///
300 /// Note that you can be a bit lazier about writing out ChannelManager than you can be with
301 /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
302 /// returning from ManyChannelMonitor::add_update_monitor, with ChannelManagers, writing updates
303 /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during
304 /// the serialization process). If the deserialized version is out-of-date compared to the
305 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
306 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
307 ///
308 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelManager), which
309 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
310 /// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
311 /// block_connected() to step towards your best block) upon deserialization before using the
312 /// object!
313 pub struct ChannelManager {
314         default_configuration: UserConfig,
315         genesis_hash: Sha256dHash,
316         fee_estimator: Arc<FeeEstimator>,
317         monitor: Arc<ManyChannelMonitor>,
318         chain_monitor: Arc<ChainWatchInterface>,
319         tx_broadcaster: Arc<BroadcasterInterface>,
320
321         latest_block_height: AtomicUsize,
322         last_block_hash: Mutex<Sha256dHash>,
323         secp_ctx: Secp256k1<secp256k1::All>,
324
325         channel_state: Mutex<ChannelHolder>,
326         our_network_key: SecretKey,
327
328         pending_events: Mutex<Vec<events::Event>>,
329         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
330         /// Essentially just when we're serializing ourselves out.
331         /// Taken first everywhere where we are making changes before any other locks.
332         total_consistency_lock: RwLock<()>,
333
334         keys_manager: Arc<KeysInterface>,
335
336         logger: Arc<Logger>,
337 }
338
339 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
340 /// HTLC's CLTV. This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
341 /// ie the node we forwarded the payment on to should always have enough room to reliably time out
342 /// the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
343 /// CLTV_CLAIM_BUFFER point (we static assert that its at least 3 blocks more).
344 const CLTV_EXPIRY_DELTA: u16 = 6 * 24 * 2; //TODO?
345 const CLTV_FAR_FAR_AWAY: u32 = 6 * 24 * 7; //TODO?
346
347 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + 2*HTLC_FAIL_TIMEOUT_BLOCKS, ie that
348 // if the next-hop peer fails the HTLC within HTLC_FAIL_TIMEOUT_BLOCKS then we'll still have
349 // HTLC_FAIL_TIMEOUT_BLOCKS left to fail it backwards ourselves before hitting the
350 // CLTV_CLAIM_BUFFER point and failing the channel on-chain to time out the HTLC.
351 #[deny(const_err)]
352 #[allow(dead_code)]
353 const CHECK_CLTV_EXPIRY_SANITY: u32 = CLTV_EXPIRY_DELTA as u32 - 2*HTLC_FAIL_TIMEOUT_BLOCKS - CLTV_CLAIM_BUFFER;
354
355 // Check for ability of an attacker to make us fail on-chain by delaying inbound claim. See
356 // ChannelMontior::would_broadcast_at_height for a description of why this is needed.
357 #[deny(const_err)]
358 #[allow(dead_code)]
359 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = CLTV_EXPIRY_DELTA as u32 - HTLC_FAIL_TIMEOUT_BLOCKS - 2*CLTV_CLAIM_BUFFER;
360
361 macro_rules! secp_call {
362         ( $res: expr, $err: expr ) => {
363                 match $res {
364                         Ok(key) => key,
365                         Err(_) => return Err($err),
366                 }
367         };
368 }
369
370 struct OnionKeys {
371         #[cfg(test)]
372         shared_secret: SharedSecret,
373         #[cfg(test)]
374         blinding_factor: [u8; 32],
375         ephemeral_pubkey: PublicKey,
376         rho: [u8; 32],
377         mu: [u8; 32],
378 }
379
380 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
381 pub struct ChannelDetails {
382         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
383         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
384         /// Note that this means this value is *not* persistent - it can change once during the
385         /// lifetime of the channel.
386         pub channel_id: [u8; 32],
387         /// The position of the funding transaction in the chain. None if the funding transaction has
388         /// not yet been confirmed and the channel fully opened.
389         pub short_channel_id: Option<u64>,
390         /// The node_id of our counterparty
391         pub remote_network_id: PublicKey,
392         /// The value, in satoshis, of this channel as appears in the funding output
393         pub channel_value_satoshis: u64,
394         /// The user_id passed in to create_channel, or 0 if the channel was inbound.
395         pub user_id: u64,
396 }
397
398 macro_rules! handle_error {
399         ($self: ident, $internal: expr, $their_node_id: expr) => {
400                 match $internal {
401                         Ok(msg) => Ok(msg),
402                         Err(MsgHandleErrInternal { err, shutdown_finish }) => {
403                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
404                                         $self.finish_force_close_channel(shutdown_res);
405                                         if let Some(update) = update_option {
406                                                 let mut channel_state = $self.channel_state.lock().unwrap();
407                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
408                                                         msg: update
409                                                 });
410                                         }
411                                 }
412                                 Err(err)
413                         },
414                 }
415         }
416 }
417
418 macro_rules! break_chan_entry {
419         ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
420                 match $res {
421                         Ok(res) => res,
422                         Err(ChannelError::Ignore(msg)) => {
423                                 break Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
424                         },
425                         Err(ChannelError::Close(msg)) => {
426                                 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
427                                 let (channel_id, mut chan) = $entry.remove_entry();
428                                 if let Some(short_id) = chan.get_short_channel_id() {
429                                         $channel_state.short_to_id.remove(&short_id);
430                                 }
431                                 break Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
432                         },
433                 }
434         }
435 }
436
437 macro_rules! try_chan_entry {
438         ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
439                 match $res {
440                         Ok(res) => res,
441                         Err(ChannelError::Ignore(msg)) => {
442                                 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
443                         },
444                         Err(ChannelError::Close(msg)) => {
445                                 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
446                                 let (channel_id, mut chan) = $entry.remove_entry();
447                                 if let Some(short_id) = chan.get_short_channel_id() {
448                                         $channel_state.short_to_id.remove(&short_id);
449                                 }
450                                 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
451                         },
452                 }
453         }
454 }
455
456 macro_rules! return_monitor_err {
457         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
458                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new())
459         };
460         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $raa_first_dropped_cs: expr) => {
461                 if $action_type != RAACommitmentOrder::RevokeAndACKFirst { panic!("Bad return_monitor_err call!"); }
462                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new(), $raa_first_dropped_cs)
463         };
464         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr) => {
465                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, $failed_forwards, $failed_fails, false)
466         };
467         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr, $raa_first_dropped_cs: expr) => {
468                 match $err {
469                         ChannelMonitorUpdateErr::PermanentFailure => {
470                                 let (channel_id, mut chan) = $entry.remove_entry();
471                                 if let Some(short_id) = chan.get_short_channel_id() {
472                                         $channel_state.short_to_id.remove(&short_id);
473                                 }
474                                 // TODO: $failed_fails is dropped here, which will cause other channels to hit the
475                                 // chain in a confused state! We need to move them into the ChannelMonitor which
476                                 // will be responsible for failing backwards once things confirm on-chain.
477                                 // It's ok that we drop $failed_forwards here - at this point we'd rather they
478                                 // broadcast HTLC-Timeout and pay the associated fees to get their funds back than
479                                 // us bother trying to claim it just to forward on to another peer. If we're
480                                 // splitting hairs we'd prefer to claim payments that were to us, but we haven't
481                                 // given up the preimage yet, so might as well just wait until the payment is
482                                 // retried, avoiding the on-chain fees.
483                                 return Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
484                         },
485                         ChannelMonitorUpdateErr::TemporaryFailure => {
486                                 $entry.get_mut().monitor_update_failed($action_type, $failed_forwards, $failed_fails, $raa_first_dropped_cs);
487                                 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore("Failed to update ChannelMonitor"), *$entry.key()));
488                         },
489                 }
490         }
491 }
492
493 // Does not break in case of TemporaryFailure!
494 macro_rules! maybe_break_monitor_err {
495         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
496                 match $err {
497                         ChannelMonitorUpdateErr::PermanentFailure => {
498                                 let (channel_id, mut chan) = $entry.remove_entry();
499                                 if let Some(short_id) = chan.get_short_channel_id() {
500                                         $channel_state.short_to_id.remove(&short_id);
501                                 }
502                                 break Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
503                         },
504                         ChannelMonitorUpdateErr::TemporaryFailure => {
505                                 $entry.get_mut().monitor_update_failed($action_type, Vec::new(), Vec::new(), false);
506                         },
507                 }
508         }
509 }
510
511 impl ChannelManager {
512         /// Constructs a new ChannelManager to hold several channels and route between them.
513         ///
514         /// This is the main "logic hub" for all channel-related actions, and implements
515         /// ChannelMessageHandler.
516         ///
517         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
518         ///
519         /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
520         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> {
521                 let secp_ctx = Secp256k1::new();
522
523                 let res = Arc::new(ChannelManager {
524                         default_configuration: config.clone(),
525                         genesis_hash: genesis_block(network).header.bitcoin_hash(),
526                         fee_estimator: feeest.clone(),
527                         monitor: monitor.clone(),
528                         chain_monitor,
529                         tx_broadcaster,
530
531                         latest_block_height: AtomicUsize::new(0), //TODO: Get an init value
532                         last_block_hash: Mutex::new(Default::default()),
533                         secp_ctx,
534
535                         channel_state: Mutex::new(ChannelHolder{
536                                 by_id: HashMap::new(),
537                                 short_to_id: HashMap::new(),
538                                 next_forward: Instant::now(),
539                                 forward_htlcs: HashMap::new(),
540                                 claimable_htlcs: HashMap::new(),
541                                 pending_msg_events: Vec::new(),
542                         }),
543                         our_network_key: keys_manager.get_node_secret(),
544
545                         pending_events: Mutex::new(Vec::new()),
546                         total_consistency_lock: RwLock::new(()),
547
548                         keys_manager,
549
550                         logger,
551                 });
552                 let weak_res = Arc::downgrade(&res);
553                 res.chain_monitor.register_listener(weak_res);
554                 Ok(res)
555         }
556
557         /// Creates a new outbound channel to the given remote node and with the given value.
558         ///
559         /// user_id will be provided back as user_channel_id in FundingGenerationReady and
560         /// FundingBroadcastSafe events to allow tracking of which events correspond with which
561         /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
562         /// may wish to avoid using 0 for user_id here.
563         ///
564         /// If successful, will generate a SendOpenChannel message event, so you should probably poll
565         /// PeerManager::process_events afterwards.
566         ///
567         /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
568         /// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
569         pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64) -> Result<(), APIError> {
570                 if channel_value_satoshis < 1000 {
571                         return Err(APIError::APIMisuseError { err: "channel_value must be at least 1000 satoshis" });
572                 }
573
574                 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)?;
575                 let res = channel.get_open_channel(self.genesis_hash.clone(), &*self.fee_estimator);
576
577                 let _ = self.total_consistency_lock.read().unwrap();
578                 let mut channel_state = self.channel_state.lock().unwrap();
579                 match channel_state.by_id.entry(channel.channel_id()) {
580                         hash_map::Entry::Occupied(_) => {
581                                 if cfg!(feature = "fuzztarget") {
582                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG" });
583                                 } else {
584                                         panic!("RNG is bad???");
585                                 }
586                         },
587                         hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
588                 }
589                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
590                         node_id: their_network_key,
591                         msg: res,
592                 });
593                 Ok(())
594         }
595
596         /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
597         /// more information.
598         pub fn list_channels(&self) -> Vec<ChannelDetails> {
599                 let channel_state = self.channel_state.lock().unwrap();
600                 let mut res = Vec::with_capacity(channel_state.by_id.len());
601                 for (channel_id, channel) in channel_state.by_id.iter() {
602                         res.push(ChannelDetails {
603                                 channel_id: (*channel_id).clone(),
604                                 short_channel_id: channel.get_short_channel_id(),
605                                 remote_network_id: channel.get_their_node_id(),
606                                 channel_value_satoshis: channel.get_value_satoshis(),
607                                 user_id: channel.get_user_id(),
608                         });
609                 }
610                 res
611         }
612
613         /// Gets the list of usable channels, in random order. Useful as an argument to
614         /// Router::get_route to ensure non-announced channels are used.
615         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
616                 let channel_state = self.channel_state.lock().unwrap();
617                 let mut res = Vec::with_capacity(channel_state.by_id.len());
618                 for (channel_id, channel) in channel_state.by_id.iter() {
619                         // Note we use is_live here instead of usable which leads to somewhat confused
620                         // internal/external nomenclature, but that's ok cause that's probably what the user
621                         // really wanted anyway.
622                         if channel.is_live() {
623                                 res.push(ChannelDetails {
624                                         channel_id: (*channel_id).clone(),
625                                         short_channel_id: channel.get_short_channel_id(),
626                                         remote_network_id: channel.get_their_node_id(),
627                                         channel_value_satoshis: channel.get_value_satoshis(),
628                                         user_id: channel.get_user_id(),
629                                 });
630                         }
631                 }
632                 res
633         }
634
635         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
636         /// will be accepted on the given channel, and after additional timeout/the closing of all
637         /// pending HTLCs, the channel will be closed on chain.
638         ///
639         /// May generate a SendShutdown message event on success, which should be relayed.
640         pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
641                 let _ = self.total_consistency_lock.read().unwrap();
642
643                 let (mut failed_htlcs, chan_option) = {
644                         let mut channel_state_lock = self.channel_state.lock().unwrap();
645                         let channel_state = channel_state_lock.borrow_parts();
646                         match channel_state.by_id.entry(channel_id.clone()) {
647                                 hash_map::Entry::Occupied(mut chan_entry) => {
648                                         let (shutdown_msg, failed_htlcs) = chan_entry.get_mut().get_shutdown()?;
649                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
650                                                 node_id: chan_entry.get().get_their_node_id(),
651                                                 msg: shutdown_msg
652                                         });
653                                         if chan_entry.get().is_shutdown() {
654                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
655                                                         channel_state.short_to_id.remove(&short_id);
656                                                 }
657                                                 (failed_htlcs, Some(chan_entry.remove_entry().1))
658                                         } else { (failed_htlcs, None) }
659                                 },
660                                 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: "No such channel"})
661                         }
662                 };
663                 for htlc_source in failed_htlcs.drain(..) {
664                         // unknown_next_peer...I dunno who that is anymore....
665                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
666                 }
667                 let chan_update = if let Some(chan) = chan_option {
668                         if let Ok(update) = self.get_channel_update(&chan) {
669                                 Some(update)
670                         } else { None }
671                 } else { None };
672
673                 if let Some(update) = chan_update {
674                         let mut channel_state = self.channel_state.lock().unwrap();
675                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
676                                 msg: update
677                         });
678                 }
679
680                 Ok(())
681         }
682
683         #[inline]
684         fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
685                 let (local_txn, mut failed_htlcs) = shutdown_res;
686                 log_trace!(self, "Finishing force-closure of channel with {} transactions to broadcast and {} HTLCs to fail", local_txn.len(), failed_htlcs.len());
687                 for htlc_source in failed_htlcs.drain(..) {
688                         // unknown_next_peer...I dunno who that is anymore....
689                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
690                 }
691                 for tx in local_txn {
692                         self.tx_broadcaster.broadcast_transaction(&tx);
693                 }
694         }
695
696         /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
697         /// the chain and rejecting new HTLCs on the given channel.
698         pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
699                 let _ = self.total_consistency_lock.read().unwrap();
700
701                 let mut chan = {
702                         let mut channel_state_lock = self.channel_state.lock().unwrap();
703                         let channel_state = channel_state_lock.borrow_parts();
704                         if let Some(chan) = channel_state.by_id.remove(channel_id) {
705                                 if let Some(short_id) = chan.get_short_channel_id() {
706                                         channel_state.short_to_id.remove(&short_id);
707                                 }
708                                 chan
709                         } else {
710                                 return;
711                         }
712                 };
713                 log_trace!(self, "Force-closing channel {}", log_bytes!(channel_id[..]));
714                 self.finish_force_close_channel(chan.force_shutdown());
715                 if let Ok(update) = self.get_channel_update(&chan) {
716                         let mut channel_state = self.channel_state.lock().unwrap();
717                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
718                                 msg: update
719                         });
720                 }
721         }
722
723         /// Force close all channels, immediately broadcasting the latest local commitment transaction
724         /// for each to the chain and rejecting new HTLCs on each.
725         pub fn force_close_all_channels(&self) {
726                 for chan in self.list_channels() {
727                         self.force_close_channel(&chan.channel_id);
728                 }
729         }
730
731         #[inline]
732         fn gen_rho_mu_from_shared_secret(shared_secret: &[u8]) -> ([u8; 32], [u8; 32]) {
733                 assert_eq!(shared_secret.len(), 32);
734                 ({
735                         let mut hmac = Hmac::new(Sha256::new(), &[0x72, 0x68, 0x6f]); // rho
736                         hmac.input(&shared_secret[..]);
737                         let mut res = [0; 32];
738                         hmac.raw_result(&mut res);
739                         res
740                 },
741                 {
742                         let mut hmac = Hmac::new(Sha256::new(), &[0x6d, 0x75]); // mu
743                         hmac.input(&shared_secret[..]);
744                         let mut res = [0; 32];
745                         hmac.raw_result(&mut res);
746                         res
747                 })
748         }
749
750         #[inline]
751         fn gen_um_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
752                 assert_eq!(shared_secret.len(), 32);
753                 let mut hmac = Hmac::new(Sha256::new(), &[0x75, 0x6d]); // um
754                 hmac.input(&shared_secret[..]);
755                 let mut res = [0; 32];
756                 hmac.raw_result(&mut res);
757                 res
758         }
759
760         #[inline]
761         fn gen_ammag_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
762                 assert_eq!(shared_secret.len(), 32);
763                 let mut hmac = Hmac::new(Sha256::new(), &[0x61, 0x6d, 0x6d, 0x61, 0x67]); // ammag
764                 hmac.input(&shared_secret[..]);
765                 let mut res = [0; 32];
766                 hmac.raw_result(&mut res);
767                 res
768         }
769
770         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
771         #[inline]
772         fn construct_onion_keys_callback<T: secp256k1::Signing, FType: FnMut(SharedSecret, [u8; 32], PublicKey, &RouteHop)> (secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey, mut callback: FType) -> Result<(), secp256k1::Error> {
773                 let mut blinded_priv = session_priv.clone();
774                 let mut blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
775
776                 for hop in route.hops.iter() {
777                         let shared_secret = SharedSecret::new(secp_ctx, &hop.pubkey, &blinded_priv);
778
779                         let mut sha = Sha256::new();
780                         sha.input(&blinded_pub.serialize()[..]);
781                         sha.input(&shared_secret[..]);
782                         let mut blinding_factor = [0u8; 32];
783                         sha.result(&mut blinding_factor);
784
785                         let ephemeral_pubkey = blinded_pub;
786
787                         blinded_priv.mul_assign(secp_ctx, &SecretKey::from_slice(secp_ctx, &blinding_factor)?)?;
788                         blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
789
790                         callback(shared_secret, blinding_factor, ephemeral_pubkey, hop);
791                 }
792
793                 Ok(())
794         }
795
796         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
797         fn construct_onion_keys<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey) -> Result<Vec<OnionKeys>, secp256k1::Error> {
798                 let mut res = Vec::with_capacity(route.hops.len());
799
800                 Self::construct_onion_keys_callback(secp_ctx, route, session_priv, |shared_secret, _blinding_factor, ephemeral_pubkey, _| {
801                         let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret[..]);
802
803                         res.push(OnionKeys {
804                                 #[cfg(test)]
805                                 shared_secret,
806                                 #[cfg(test)]
807                                 blinding_factor: _blinding_factor,
808                                 ephemeral_pubkey,
809                                 rho,
810                                 mu,
811                         });
812                 })?;
813
814                 Ok(res)
815         }
816
817         /// returns the hop data, as well as the first-hop value_msat and CLTV value we should send.
818         fn build_onion_payloads(route: &Route, starting_htlc_offset: u32) -> Result<(Vec<msgs::OnionHopData>, u64, u32), APIError> {
819                 let mut cur_value_msat = 0u64;
820                 let mut cur_cltv = starting_htlc_offset;
821                 let mut last_short_channel_id = 0;
822                 let mut res: Vec<msgs::OnionHopData> = Vec::with_capacity(route.hops.len());
823                 internal_traits::test_no_dealloc::<msgs::OnionHopData>(None);
824                 unsafe { res.set_len(route.hops.len()); }
825
826                 for (idx, hop) in route.hops.iter().enumerate().rev() {
827                         // First hop gets special values so that it can check, on receipt, that everything is
828                         // exactly as it should be (and the next hop isn't trying to probe to find out if we're
829                         // the intended recipient).
830                         let value_msat = if cur_value_msat == 0 { hop.fee_msat } else { cur_value_msat };
831                         let cltv = if cur_cltv == starting_htlc_offset { hop.cltv_expiry_delta + starting_htlc_offset } else { cur_cltv };
832                         res[idx] = msgs::OnionHopData {
833                                 realm: 0,
834                                 data: msgs::OnionRealm0HopData {
835                                         short_channel_id: last_short_channel_id,
836                                         amt_to_forward: value_msat,
837                                         outgoing_cltv_value: cltv,
838                                 },
839                                 hmac: [0; 32],
840                         };
841                         cur_value_msat += hop.fee_msat;
842                         if cur_value_msat >= 21000000 * 100000000 * 1000 {
843                                 return Err(APIError::RouteError{err: "Channel fees overflowed?!"});
844                         }
845                         cur_cltv += hop.cltv_expiry_delta as u32;
846                         if cur_cltv >= 500000000 {
847                                 return Err(APIError::RouteError{err: "Channel CLTV overflowed?!"});
848                         }
849                         last_short_channel_id = hop.short_channel_id;
850                 }
851                 Ok((res, cur_value_msat, cur_cltv))
852         }
853
854         #[inline]
855         fn shift_arr_right(arr: &mut [u8; 20*65]) {
856                 unsafe {
857                         ptr::copy(arr[0..].as_ptr(), arr[65..].as_mut_ptr(), 19*65);
858                 }
859                 for i in 0..65 {
860                         arr[i] = 0;
861                 }
862         }
863
864         #[inline]
865         fn xor_bufs(dst: &mut[u8], src: &[u8]) {
866                 assert_eq!(dst.len(), src.len());
867
868                 for i in 0..dst.len() {
869                         dst[i] ^= src[i];
870                 }
871         }
872
873         const ZERO:[u8; 21*65] = [0; 21*65];
874         fn construct_onion_packet(mut payloads: Vec<msgs::OnionHopData>, onion_keys: Vec<OnionKeys>, associated_data: &PaymentHash) -> msgs::OnionPacket {
875                 let mut buf = Vec::with_capacity(21*65);
876                 buf.resize(21*65, 0);
877
878                 let filler = {
879                         let iters = payloads.len() - 1;
880                         let end_len = iters * 65;
881                         let mut res = Vec::with_capacity(end_len);
882                         res.resize(end_len, 0);
883
884                         for (i, keys) in onion_keys.iter().enumerate() {
885                                 if i == payloads.len() - 1 { continue; }
886                                 let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
887                                 chacha.process(&ChannelManager::ZERO, &mut buf); // We don't have a seek function :(
888                                 ChannelManager::xor_bufs(&mut res[0..(i + 1)*65], &buf[(20 - i)*65..21*65]);
889                         }
890                         res
891                 };
892
893                 let mut packet_data = [0; 20*65];
894                 let mut hmac_res = [0; 32];
895
896                 for (i, (payload, keys)) in payloads.iter_mut().zip(onion_keys.iter()).rev().enumerate() {
897                         ChannelManager::shift_arr_right(&mut packet_data);
898                         payload.hmac = hmac_res;
899                         packet_data[0..65].copy_from_slice(&payload.encode()[..]);
900
901                         let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
902                         chacha.process(&packet_data, &mut buf[0..20*65]);
903                         packet_data[..].copy_from_slice(&buf[0..20*65]);
904
905                         if i == 0 {
906                                 packet_data[20*65 - filler.len()..20*65].copy_from_slice(&filler[..]);
907                         }
908
909                         let mut hmac = Hmac::new(Sha256::new(), &keys.mu);
910                         hmac.input(&packet_data);
911                         hmac.input(&associated_data.0[..]);
912                         hmac.raw_result(&mut hmac_res);
913                 }
914
915                 msgs::OnionPacket{
916                         version: 0,
917                         public_key: Ok(onion_keys.first().unwrap().ephemeral_pubkey),
918                         hop_data: packet_data,
919                         hmac: hmac_res,
920                 }
921         }
922
923         /// Encrypts a failure packet. raw_packet can either be a
924         /// msgs::DecodedOnionErrorPacket.encode() result or a msgs::OnionErrorPacket.data element.
925         fn encrypt_failure_packet(shared_secret: &[u8], raw_packet: &[u8]) -> msgs::OnionErrorPacket {
926                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
927
928                 let mut packet_crypted = Vec::with_capacity(raw_packet.len());
929                 packet_crypted.resize(raw_packet.len(), 0);
930                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
931                 chacha.process(&raw_packet, &mut packet_crypted[..]);
932                 msgs::OnionErrorPacket {
933                         data: packet_crypted,
934                 }
935         }
936
937         fn build_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::DecodedOnionErrorPacket {
938                 assert_eq!(shared_secret.len(), 32);
939                 assert!(failure_data.len() <= 256 - 2);
940
941                 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
942
943                 let failuremsg = {
944                         let mut res = Vec::with_capacity(2 + failure_data.len());
945                         res.push(((failure_type >> 8) & 0xff) as u8);
946                         res.push(((failure_type >> 0) & 0xff) as u8);
947                         res.extend_from_slice(&failure_data[..]);
948                         res
949                 };
950                 let pad = {
951                         let mut res = Vec::with_capacity(256 - 2 - failure_data.len());
952                         res.resize(256 - 2 - failure_data.len(), 0);
953                         res
954                 };
955                 let mut packet = msgs::DecodedOnionErrorPacket {
956                         hmac: [0; 32],
957                         failuremsg: failuremsg,
958                         pad: pad,
959                 };
960
961                 let mut hmac = Hmac::new(Sha256::new(), &um);
962                 hmac.input(&packet.encode()[32..]);
963                 hmac.raw_result(&mut packet.hmac);
964
965                 packet
966         }
967
968         #[inline]
969         fn build_first_hop_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::OnionErrorPacket {
970                 let failure_packet = ChannelManager::build_failure_packet(shared_secret, failure_type, failure_data);
971                 ChannelManager::encrypt_failure_packet(shared_secret, &failure_packet.encode()[..])
972         }
973
974         fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder>) {
975                 macro_rules! get_onion_hash {
976                         () => {
977                                 {
978                                         let mut sha = Sha256::new();
979                                         sha.input(&msg.onion_routing_packet.hop_data);
980                                         let mut onion_hash = [0; 32];
981                                         sha.result(&mut onion_hash);
982                                         onion_hash
983                                 }
984                         }
985                 }
986
987                 if let Err(_) = msg.onion_routing_packet.public_key {
988                         log_info!(self, "Failed to accept/forward incoming HTLC with invalid ephemeral pubkey");
989                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
990                                 channel_id: msg.channel_id,
991                                 htlc_id: msg.htlc_id,
992                                 sha256_of_onion: get_onion_hash!(),
993                                 failure_code: 0x8000 | 0x4000 | 6,
994                         })), self.channel_state.lock().unwrap());
995                 }
996
997                 let shared_secret = {
998                         let mut arr = [0; 32];
999                         arr.copy_from_slice(&SharedSecret::new(&self.secp_ctx, &msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key)[..]);
1000                         arr
1001                 };
1002                 let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
1003
1004                 let mut channel_state = None;
1005                 macro_rules! return_err {
1006                         ($msg: expr, $err_code: expr, $data: expr) => {
1007                                 {
1008                                         log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
1009                                         if channel_state.is_none() {
1010                                                 channel_state = Some(self.channel_state.lock().unwrap());
1011                                         }
1012                                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
1013                                                 channel_id: msg.channel_id,
1014                                                 htlc_id: msg.htlc_id,
1015                                                 reason: ChannelManager::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
1016                                         })), channel_state.unwrap());
1017                                 }
1018                         }
1019                 }
1020
1021                 if msg.onion_routing_packet.version != 0 {
1022                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
1023                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
1024                         //the hash doesn't really serve any purpuse - in the case of hashing all data, the
1025                         //receiving node would have to brute force to figure out which version was put in the
1026                         //packet by the node that send us the message, in the case of hashing the hop_data, the
1027                         //node knows the HMAC matched, so they already know what is there...
1028                         return_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4, &get_onion_hash!());
1029                 }
1030
1031                 let mut hmac = Hmac::new(Sha256::new(), &mu);
1032                 hmac.input(&msg.onion_routing_packet.hop_data);
1033                 hmac.input(&msg.payment_hash.0[..]);
1034                 if hmac.result() != MacResult::new(&msg.onion_routing_packet.hmac) {
1035                         return_err!("HMAC Check failed", 0x8000 | 0x4000 | 5, &get_onion_hash!());
1036                 }
1037
1038                 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
1039                 let next_hop_data = {
1040                         let mut decoded = [0; 65];
1041                         chacha.process(&msg.onion_routing_packet.hop_data[0..65], &mut decoded);
1042                         match msgs::OnionHopData::read(&mut Cursor::new(&decoded[..])) {
1043                                 Err(err) => {
1044                                         let error_code = match err {
1045                                                 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
1046                                                 _ => 0x2000 | 2, // Should never happen
1047                                         };
1048                                         return_err!("Unable to decode our hop data", error_code, &[0;0]);
1049                                 },
1050                                 Ok(msg) => msg
1051                         }
1052                 };
1053
1054                 let pending_forward_info = if next_hop_data.hmac == [0; 32] {
1055                                 // OUR PAYMENT!
1056                                 // final_expiry_too_soon
1057                                 if (msg.cltv_expiry as u64) < self.latest_block_height.load(Ordering::Acquire) as u64 + (CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS) as u64 {
1058                                         return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
1059                                 }
1060                                 // final_incorrect_htlc_amount
1061                                 if next_hop_data.data.amt_to_forward > msg.amount_msat {
1062                                         return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
1063                                 }
1064                                 // final_incorrect_cltv_expiry
1065                                 if next_hop_data.data.outgoing_cltv_value != msg.cltv_expiry {
1066                                         return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
1067                                 }
1068
1069                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
1070                                 // message, however that would leak that we are the recipient of this payment, so
1071                                 // instead we stay symmetric with the forwarding case, only responding (after a
1072                                 // delay) once they've send us a commitment_signed!
1073
1074                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1075                                         onion_packet: None,
1076                                         payment_hash: msg.payment_hash.clone(),
1077                                         short_channel_id: 0,
1078                                         incoming_shared_secret: shared_secret,
1079                                         amt_to_forward: next_hop_data.data.amt_to_forward,
1080                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1081                                 })
1082                         } else {
1083                                 let mut new_packet_data = [0; 20*65];
1084                                 chacha.process(&msg.onion_routing_packet.hop_data[65..], &mut new_packet_data[0..19*65]);
1085                                 chacha.process(&ChannelManager::ZERO[0..65], &mut new_packet_data[19*65..]);
1086
1087                                 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
1088
1089                                 let blinding_factor = {
1090                                         let mut sha = Sha256::new();
1091                                         sha.input(&new_pubkey.serialize()[..]);
1092                                         sha.input(&shared_secret);
1093                                         let mut res = [0u8; 32];
1094                                         sha.result(&mut res);
1095                                         match SecretKey::from_slice(&self.secp_ctx, &res) {
1096                                                 Err(_) => {
1097                                                         return_err!("Blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
1098                                                 },
1099                                                 Ok(key) => key
1100                                         }
1101                                 };
1102
1103                                 if let Err(_) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor) {
1104                                         return_err!("New blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
1105                                 }
1106
1107                                 let outgoing_packet = msgs::OnionPacket {
1108                                         version: 0,
1109                                         public_key: Ok(new_pubkey),
1110                                         hop_data: new_packet_data,
1111                                         hmac: next_hop_data.hmac.clone(),
1112                                 };
1113
1114                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1115                                         onion_packet: Some(outgoing_packet),
1116                                         payment_hash: msg.payment_hash.clone(),
1117                                         short_channel_id: next_hop_data.data.short_channel_id,
1118                                         incoming_shared_secret: shared_secret,
1119                                         amt_to_forward: next_hop_data.data.amt_to_forward,
1120                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1121                                 })
1122                         };
1123
1124                 channel_state = Some(self.channel_state.lock().unwrap());
1125                 if let &PendingHTLCStatus::Forward(PendingForwardHTLCInfo { ref onion_packet, ref short_channel_id, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
1126                         if onion_packet.is_some() { // If short_channel_id is 0 here, we'll reject them in the body here
1127                                 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
1128                                 let forwarding_id = match id_option {
1129                                         None => { // unknown_next_peer
1130                                                 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
1131                                         },
1132                                         Some(id) => id.clone(),
1133                                 };
1134                                 if let Some((err, code, chan_update)) = loop {
1135                                         let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
1136
1137                                         // Note that we could technically not return an error yet here and just hope
1138                                         // that the connection is reestablished or monitor updated by the time we get
1139                                         // around to doing the actual forward, but better to fail early if we can and
1140                                         // hopefully an attacker trying to path-trace payments cannot make this occur
1141                                         // on a small/per-node/per-channel scale.
1142                                         if !chan.is_live() { // channel_disabled
1143                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
1144                                         }
1145                                         if *amt_to_forward < chan.get_their_htlc_minimum_msat() { // amount_below_minimum
1146                                                 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
1147                                         }
1148                                         let fee = amt_to_forward.checked_mul(chan.get_fee_proportional_millionths() as u64).and_then(|prop_fee| { (prop_fee / 1000000).checked_add(chan.get_our_fee_base_msat(&*self.fee_estimator) as u64) });
1149                                         if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
1150                                                 break Some(("Prior hop has deviated from specified fees parameters or origin node has obsolete ones", 0x1000 | 12, Some(self.get_channel_update(chan).unwrap())));
1151                                         }
1152                                         if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 { // incorrect_cltv_expiry
1153                                                 break Some(("Forwarding node has tampered with the intended HTLC values or origin node has an obsolete cltv_expiry_delta", 0x1000 | 13, Some(self.get_channel_update(chan).unwrap())));
1154                                         }
1155                                         let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1156                                         // We want to have at least HTLC_FAIL_TIMEOUT_BLOCKS to fail prior to going on chain CLAIM_BUFFER blocks before expiration
1157                                         if msg.cltv_expiry <= cur_height + CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS as u32 { // expiry_too_soon
1158                                                 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1159                                         }
1160                                         if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
1161                                                 break Some(("CLTV expiry is too far in the future", 21, None));
1162                                         }
1163                                         break None;
1164                                 }
1165                                 {
1166                                         let mut res = Vec::with_capacity(8 + 128);
1167                                         if code == 0x1000 | 11 || code == 0x1000 | 12 {
1168                                                 res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
1169                                         }
1170                                         else if code == 0x1000 | 13 {
1171                                                 res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
1172                                         }
1173                                         if let Some(chan_update) = chan_update {
1174                                                 res.extend_from_slice(&chan_update.encode_with_len()[..]);
1175                                         }
1176                                         return_err!(err, code, &res[..]);
1177                                 }
1178                         }
1179                 }
1180
1181                 (pending_forward_info, channel_state.unwrap())
1182         }
1183
1184         /// only fails if the channel does not yet have an assigned short_id
1185         /// May be called with channel_state already locked!
1186         fn get_channel_update(&self, chan: &Channel) -> Result<msgs::ChannelUpdate, HandleError> {
1187                 let short_channel_id = match chan.get_short_channel_id() {
1188                         None => return Err(HandleError{err: "Channel not yet established", action: None}),
1189                         Some(id) => id,
1190                 };
1191
1192                 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_their_node_id().serialize()[..];
1193
1194                 let unsigned = msgs::UnsignedChannelUpdate {
1195                         chain_hash: self.genesis_hash,
1196                         short_channel_id: short_channel_id,
1197                         timestamp: chan.get_channel_update_count(),
1198                         flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
1199                         cltv_expiry_delta: CLTV_EXPIRY_DELTA,
1200                         htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
1201                         fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
1202                         fee_proportional_millionths: chan.get_fee_proportional_millionths(),
1203                         excess_data: Vec::new(),
1204                 };
1205
1206                 let msg_hash = Sha256dHash::from_data(&unsigned.encode()[..]);
1207                 let sig = self.secp_ctx.sign(&Message::from_slice(&msg_hash[..]).unwrap(), &self.our_network_key);
1208
1209                 Ok(msgs::ChannelUpdate {
1210                         signature: sig,
1211                         contents: unsigned
1212                 })
1213         }
1214
1215         /// Sends a payment along a given route.
1216         ///
1217         /// Value parameters are provided via the last hop in route, see documentation for RouteHop
1218         /// fields for more info.
1219         ///
1220         /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
1221         /// payment), we don't do anything to stop you! We always try to ensure that if the provided
1222         /// next hop knows the preimage to payment_hash they can claim an additional amount as
1223         /// specified in the last hop in the route! Thus, you should probably do your own
1224         /// payment_preimage tracking (which you should already be doing as they represent "proof of
1225         /// payment") and prevent double-sends yourself.
1226         ///
1227         /// May generate a SendHTLCs message event on success, which should be relayed.
1228         ///
1229         /// Raises APIError::RoutError when invalid route or forward parameter
1230         /// (cltv_delta, fee, node public key) is specified.
1231         /// Raises APIError::ChannelUnavailable if the next-hop channel is not available for updates
1232         /// (including due to previous monitor update failure or new permanent monitor update failure).
1233         /// Raised APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
1234         /// relevant updates.
1235         ///
1236         /// In case of APIError::RouteError/APIError::ChannelUnavailable, the payment send has failed
1237         /// and you may wish to retry via a different route immediately.
1238         /// In case of APIError::MonitorUpdateFailed, the commitment update has been irrevocably
1239         /// committed on our end and we're just waiting for a monitor update to send it. Do NOT retry
1240         /// the payment via a different route unless you intend to pay twice!
1241         pub fn send_payment(&self, route: Route, payment_hash: PaymentHash) -> Result<(), APIError> {
1242                 if route.hops.len() < 1 || route.hops.len() > 20 {
1243                         return Err(APIError::RouteError{err: "Route didn't go anywhere/had bogus size"});
1244                 }
1245                 let our_node_id = self.get_our_node_id();
1246                 for (idx, hop) in route.hops.iter().enumerate() {
1247                         if idx != route.hops.len() - 1 && hop.pubkey == our_node_id {
1248                                 return Err(APIError::RouteError{err: "Route went through us but wasn't a simple rebalance loop to us"});
1249                         }
1250                 }
1251
1252                 let session_priv = self.keys_manager.get_session_key();
1253
1254                 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1255
1256                 let onion_keys = secp_call!(ChannelManager::construct_onion_keys(&self.secp_ctx, &route, &session_priv),
1257                                 APIError::RouteError{err: "Pubkey along hop was maliciously selected"});
1258                 let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height)?;
1259                 let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
1260
1261                 let _ = self.total_consistency_lock.read().unwrap();
1262
1263                 let err: Result<(), _> = loop {
1264                         let mut channel_lock = self.channel_state.lock().unwrap();
1265
1266                         let id = match channel_lock.short_to_id.get(&route.hops.first().unwrap().short_channel_id) {
1267                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!"}),
1268                                 Some(id) => id.clone(),
1269                         };
1270
1271                         let channel_state = channel_lock.borrow_parts();
1272                         if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) {
1273                                 match {
1274                                         if chan.get().get_their_node_id() != route.hops.first().unwrap().pubkey {
1275                                                 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1276                                         }
1277                                         if !chan.get().is_live() {
1278                                                 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!"});
1279                                         }
1280                                         break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1281                                                 route: route.clone(),
1282                                                 session_priv: session_priv.clone(),
1283                                                 first_hop_htlc_msat: htlc_msat,
1284                                         }, onion_packet), channel_state, chan)
1285                                 } {
1286                                         Some((update_add, commitment_signed, chan_monitor)) => {
1287                                                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1288                                                         maybe_break_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst);
1289                                                         // Note that MonitorUpdateFailed here indicates (per function docs)
1290                                                         // that we will resent the commitment update once we unfree monitor
1291                                                         // updating, so we have to take special care that we don't return
1292                                                         // something else in case we will resend later!
1293                                                         return Err(APIError::MonitorUpdateFailed);
1294                                                 }
1295
1296                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1297                                                         node_id: route.hops.first().unwrap().pubkey,
1298                                                         updates: msgs::CommitmentUpdate {
1299                                                                 update_add_htlcs: vec![update_add],
1300                                                                 update_fulfill_htlcs: Vec::new(),
1301                                                                 update_fail_htlcs: Vec::new(),
1302                                                                 update_fail_malformed_htlcs: Vec::new(),
1303                                                                 update_fee: None,
1304                                                                 commitment_signed,
1305                                                         },
1306                                                 });
1307                                         },
1308                                         None => {},
1309                                 }
1310                         } else { unreachable!(); }
1311                         return Ok(());
1312                 };
1313
1314                 match handle_error!(self, err, route.hops.first().unwrap().pubkey) {
1315                         Ok(_) => unreachable!(),
1316                         Err(e) => {
1317                                 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
1318                                 } else {
1319                                         log_error!(self, "Got bad keys: {}!", e.err);
1320                                         let mut channel_state = self.channel_state.lock().unwrap();
1321                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1322                                                 node_id: route.hops.first().unwrap().pubkey,
1323                                                 action: e.action,
1324                                         });
1325                                 }
1326                                 Err(APIError::ChannelUnavailable { err: e.err })
1327                         },
1328                 }
1329         }
1330
1331         /// Call this upon creation of a funding transaction for the given channel.
1332         ///
1333         /// Note that ALL inputs in the transaction pointed to by funding_txo MUST spend SegWit outputs
1334         /// or your counterparty can steal your funds!
1335         ///
1336         /// Panics if a funding transaction has already been provided for this channel.
1337         ///
1338         /// May panic if the funding_txo is duplicative with some other channel (note that this should
1339         /// be trivially prevented by using unique funding transaction keys per-channel).
1340         pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1341                 let _ = self.total_consistency_lock.read().unwrap();
1342
1343                 let (chan, msg, chan_monitor) = {
1344                         let (res, chan) = {
1345                                 let mut channel_state = self.channel_state.lock().unwrap();
1346                                 match channel_state.by_id.remove(temporary_channel_id) {
1347                                         Some(mut chan) => {
1348                                                 (chan.get_outbound_funding_created(funding_txo)
1349                                                         .map_err(|e| if let ChannelError::Close(msg) = e {
1350                                                                 MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.force_shutdown(), None)
1351                                                         } else { unreachable!(); })
1352                                                 , chan)
1353                                         },
1354                                         None => return
1355                                 }
1356                         };
1357                         match handle_error!(self, res, chan.get_their_node_id()) {
1358                                 Ok(funding_msg) => {
1359                                         (chan, funding_msg.0, funding_msg.1)
1360                                 },
1361                                 Err(e) => {
1362                                         log_error!(self, "Got bad signatures: {}!", e.err);
1363                                         let mut channel_state = self.channel_state.lock().unwrap();
1364                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1365                                                 node_id: chan.get_their_node_id(),
1366                                                 action: e.action,
1367                                         });
1368                                         return;
1369                                 },
1370                         }
1371                 };
1372                 // Because we have exclusive ownership of the channel here we can release the channel_state
1373                 // lock before add_update_monitor
1374                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1375                         unimplemented!();
1376                 }
1377
1378                 let mut channel_state = self.channel_state.lock().unwrap();
1379                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
1380                         node_id: chan.get_their_node_id(),
1381                         msg: msg,
1382                 });
1383                 match channel_state.by_id.entry(chan.channel_id()) {
1384                         hash_map::Entry::Occupied(_) => {
1385                                 panic!("Generated duplicate funding txid?");
1386                         },
1387                         hash_map::Entry::Vacant(e) => {
1388                                 e.insert(chan);
1389                         }
1390                 }
1391         }
1392
1393         fn get_announcement_sigs(&self, chan: &Channel) -> Option<msgs::AnnouncementSignatures> {
1394                 if !chan.should_announce() { return None }
1395
1396                 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1397                         Ok(res) => res,
1398                         Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1399                 };
1400                 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
1401                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1402
1403                 Some(msgs::AnnouncementSignatures {
1404                         channel_id: chan.channel_id(),
1405                         short_channel_id: chan.get_short_channel_id().unwrap(),
1406                         node_signature: our_node_sig,
1407                         bitcoin_signature: our_bitcoin_sig,
1408                 })
1409         }
1410
1411         /// Processes HTLCs which are pending waiting on random forward delay.
1412         ///
1413         /// Should only really ever be called in response to an PendingHTLCsForwardable event.
1414         /// Will likely generate further events.
1415         pub fn process_pending_htlc_forwards(&self) {
1416                 let _ = self.total_consistency_lock.read().unwrap();
1417
1418                 let mut new_events = Vec::new();
1419                 let mut failed_forwards = Vec::new();
1420                 {
1421                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1422                         let channel_state = channel_state_lock.borrow_parts();
1423
1424                         if cfg!(not(feature = "fuzztarget")) && Instant::now() < *channel_state.next_forward {
1425                                 return;
1426                         }
1427
1428                         for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1429                                 if short_chan_id != 0 {
1430                                         let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1431                                                 Some(chan_id) => chan_id.clone(),
1432                                                 None => {
1433                                                         failed_forwards.reserve(pending_forwards.len());
1434                                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1435                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1436                                                                         short_channel_id: prev_short_channel_id,
1437                                                                         htlc_id: prev_htlc_id,
1438                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1439                                                                 });
1440                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
1441                                                         }
1442                                                         continue;
1443                                                 }
1444                                         };
1445                                         let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();
1446
1447                                         let mut add_htlc_msgs = Vec::new();
1448                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1449                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1450                                                         short_channel_id: prev_short_channel_id,
1451                                                         htlc_id: prev_htlc_id,
1452                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1453                                                 });
1454                                                 match forward_chan.send_htlc(forward_info.amt_to_forward, forward_info.payment_hash, forward_info.outgoing_cltv_value, htlc_source.clone(), forward_info.onion_packet.unwrap()) {
1455                                                         Err(_e) => {
1456                                                                 let chan_update = self.get_channel_update(forward_chan).unwrap();
1457                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x1000 | 7, Some(chan_update)));
1458                                                                 continue;
1459                                                         },
1460                                                         Ok(update_add) => {
1461                                                                 match update_add {
1462                                                                         Some(msg) => { add_htlc_msgs.push(msg); },
1463                                                                         None => {
1464                                                                                 // Nothing to do here...we're waiting on a remote
1465                                                                                 // revoke_and_ack before we can add anymore HTLCs. The Channel
1466                                                                                 // will automatically handle building the update_add_htlc and
1467                                                                                 // commitment_signed messages when we can.
1468                                                                                 // TODO: Do some kind of timer to set the channel as !is_live()
1469                                                                                 // as we don't really want others relying on us relaying through
1470                                                                                 // this channel currently :/.
1471                                                                         }
1472                                                                 }
1473                                                         }
1474                                                 }
1475                                         }
1476
1477                                         if !add_htlc_msgs.is_empty() {
1478                                                 let (commitment_msg, monitor) = match forward_chan.send_commitment() {
1479                                                         Ok(res) => res,
1480                                                         Err(e) => {
1481                                                                 if let ChannelError::Ignore(_) = e {
1482                                                                         panic!("Stated return value requirements in send_commitment() were not met");
1483                                                                 }
1484                                                                 //TODO: Handle...this is bad!
1485                                                                 continue;
1486                                                         },
1487                                                 };
1488                                                 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
1489                                                         unimplemented!();
1490                                                 }
1491                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1492                                                         node_id: forward_chan.get_their_node_id(),
1493                                                         updates: msgs::CommitmentUpdate {
1494                                                                 update_add_htlcs: add_htlc_msgs,
1495                                                                 update_fulfill_htlcs: Vec::new(),
1496                                                                 update_fail_htlcs: Vec::new(),
1497                                                                 update_fail_malformed_htlcs: Vec::new(),
1498                                                                 update_fee: None,
1499                                                                 commitment_signed: commitment_msg,
1500                                                         },
1501                                                 });
1502                                         }
1503                                 } else {
1504                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1505                                                 let prev_hop_data = HTLCPreviousHopData {
1506                                                         short_channel_id: prev_short_channel_id,
1507                                                         htlc_id: prev_htlc_id,
1508                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1509                                                 };
1510                                                 match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
1511                                                         hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(prev_hop_data),
1512                                                         hash_map::Entry::Vacant(entry) => { entry.insert(vec![prev_hop_data]); },
1513                                                 };
1514                                                 new_events.push(events::Event::PaymentReceived {
1515                                                         payment_hash: forward_info.payment_hash,
1516                                                         amt: forward_info.amt_to_forward,
1517                                                 });
1518                                         }
1519                                 }
1520                         }
1521                 }
1522
1523                 for (htlc_source, payment_hash, failure_code, update) in failed_forwards.drain(..) {
1524                         match update {
1525                                 None => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code, data: Vec::new() }),
1526                                 Some(chan_update) => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code, data: chan_update.encode_with_len() }),
1527                         };
1528                 }
1529
1530                 if new_events.is_empty() { return }
1531                 let mut events = self.pending_events.lock().unwrap();
1532                 events.append(&mut new_events);
1533         }
1534
1535         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect after a PaymentReceived event.
1536         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash, reason: PaymentFailReason) -> bool {
1537                 let _ = self.total_consistency_lock.read().unwrap();
1538
1539                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1540                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(payment_hash);
1541                 if let Some(mut sources) = removed_source {
1542                         for htlc_with_hash in sources.drain(..) {
1543                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1544                                 self.fail_htlc_backwards_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_hash, HTLCFailReason::Reason { failure_code: if reason == PaymentFailReason::PreimageUnknown {0x4000 | 15} else {0x4000 | 16}, data: Vec::new() });
1545                         }
1546                         true
1547                 } else { false }
1548         }
1549
1550         /// Fails an HTLC backwards to the sender of it to us.
1551         /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
1552         /// There are several callsites that do stupid things like loop over a list of payment_hashes
1553         /// to fail and take the channel_state lock for each iteration (as we take ownership and may
1554         /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
1555         /// still-available channels.
1556         fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
1557                 match source {
1558                         HTLCSource::OutboundRoute { .. } => {
1559                                 log_trace!(self, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1560                                 mem::drop(channel_state_lock);
1561                                 if let &HTLCFailReason::ErrorPacket { ref err } = &onion_error {
1562                                         let (channel_update, payment_retryable) = self.process_onion_failure(&source, err.data.clone());
1563                                         if let Some(update) = channel_update {
1564                                                 self.channel_state.lock().unwrap().pending_msg_events.push(
1565                                                         events::MessageSendEvent::PaymentFailureNetworkUpdate {
1566                                                                 update,
1567                                                         }
1568                                                 );
1569                                         }
1570                                         self.pending_events.lock().unwrap().push(events::Event::PaymentFailed {
1571                                                 payment_hash: payment_hash.clone(),
1572                                                 rejected_by_dest: !payment_retryable,
1573                                         });
1574                                 } else {
1575                                         //TODO: Pass this back (see GH #243)
1576                                         self.pending_events.lock().unwrap().push(events::Event::PaymentFailed {
1577                                                 payment_hash: payment_hash.clone(),
1578                                                 rejected_by_dest: false, // We failed it ourselves, can't blame them
1579                                         });
1580                                 }
1581                         },
1582                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
1583                                 let err_packet = match onion_error {
1584                                         HTLCFailReason::Reason { failure_code, data } => {
1585                                                 log_trace!(self, "Failing HTLC with payment_hash {} backwards from us with code {}", log_bytes!(payment_hash.0), failure_code);
1586                                                 let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1587                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1588                                         },
1589                                         HTLCFailReason::ErrorPacket { err } => {
1590                                                 log_trace!(self, "Failing HTLC with payment_hash {} backwards with pre-built ErrorPacket", log_bytes!(payment_hash.0));
1591                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1592                                         }
1593                                 };
1594
1595                                 let channel_state = channel_state_lock.borrow_parts();
1596
1597                                 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1598                                         Some(chan_id) => chan_id.clone(),
1599                                         None => return
1600                                 };
1601
1602                                 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1603                                 match chan.get_update_fail_htlc_and_commit(htlc_id, err_packet) {
1604                                         Ok(Some((msg, commitment_msg, chan_monitor))) => {
1605                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1606                                                         unimplemented!();
1607                                                 }
1608                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1609                                                         node_id: chan.get_their_node_id(),
1610                                                         updates: msgs::CommitmentUpdate {
1611                                                                 update_add_htlcs: Vec::new(),
1612                                                                 update_fulfill_htlcs: Vec::new(),
1613                                                                 update_fail_htlcs: vec![msg],
1614                                                                 update_fail_malformed_htlcs: Vec::new(),
1615                                                                 update_fee: None,
1616                                                                 commitment_signed: commitment_msg,
1617                                                         },
1618                                                 });
1619                                         },
1620                                         Ok(None) => {},
1621                                         Err(_e) => {
1622                                                 //TODO: Do something with e?
1623                                                 return;
1624                                         },
1625                                 }
1626                         },
1627                 }
1628         }
1629
1630         /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1631         /// generating message events for the net layer to claim the payment, if possible. Thus, you
1632         /// should probably kick the net layer to go send messages if this returns true!
1633         ///
1634         /// May panic if called except in response to a PaymentReceived event.
1635         pub fn claim_funds(&self, payment_preimage: PaymentPreimage) -> bool {
1636                 let mut sha = Sha256::new();
1637                 sha.input(&payment_preimage.0[..]);
1638                 let mut payment_hash = PaymentHash([0; 32]);
1639                 sha.result(&mut payment_hash.0[..]);
1640
1641                 let _ = self.total_consistency_lock.read().unwrap();
1642
1643                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1644                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&payment_hash);
1645                 if let Some(mut sources) = removed_source {
1646                         for htlc_with_hash in sources.drain(..) {
1647                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1648                                 self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_preimage);
1649                         }
1650                         true
1651                 } else { false }
1652         }
1653         fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_preimage: PaymentPreimage) {
1654                 match source {
1655                         HTLCSource::OutboundRoute { .. } => {
1656                                 mem::drop(channel_state_lock);
1657                                 let mut pending_events = self.pending_events.lock().unwrap();
1658                                 pending_events.push(events::Event::PaymentSent {
1659                                         payment_preimage
1660                                 });
1661                         },
1662                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, .. }) => {
1663                                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1664                                 let channel_state = channel_state_lock.borrow_parts();
1665
1666                                 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1667                                         Some(chan_id) => chan_id.clone(),
1668                                         None => {
1669                                                 // TODO: There is probably a channel manager somewhere that needs to
1670                                                 // learn the preimage as the channel already hit the chain and that's
1671                                                 // why its missing.
1672                                                 return
1673                                         }
1674                                 };
1675
1676                                 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1677                                 match chan.get_update_fulfill_htlc_and_commit(htlc_id, payment_preimage) {
1678                                         Ok((msgs, monitor_option)) => {
1679                                                 if let Some(chan_monitor) = monitor_option {
1680                                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1681                                                                 unimplemented!();// but def dont push the event...
1682                                                         }
1683                                                 }
1684                                                 if let Some((msg, commitment_signed)) = msgs {
1685                                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1686                                                                 node_id: chan.get_their_node_id(),
1687                                                                 updates: msgs::CommitmentUpdate {
1688                                                                         update_add_htlcs: Vec::new(),
1689                                                                         update_fulfill_htlcs: vec![msg],
1690                                                                         update_fail_htlcs: Vec::new(),
1691                                                                         update_fail_malformed_htlcs: Vec::new(),
1692                                                                         update_fee: None,
1693                                                                         commitment_signed,
1694                                                                 }
1695                                                         });
1696                                                 }
1697                                         },
1698                                         Err(_e) => {
1699                                                 // TODO: There is probably a channel manager somewhere that needs to
1700                                                 // learn the preimage as the channel may be about to hit the chain.
1701                                                 //TODO: Do something with e?
1702                                                 return
1703                                         },
1704                                 }
1705                         },
1706                 }
1707         }
1708
1709         /// Gets the node_id held by this ChannelManager
1710         pub fn get_our_node_id(&self) -> PublicKey {
1711                 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
1712         }
1713
1714         /// Used to restore channels to normal operation after a
1715         /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
1716         /// operation.
1717         pub fn test_restore_channel_monitor(&self) {
1718                 let mut close_results = Vec::new();
1719                 let mut htlc_forwards = Vec::new();
1720                 let mut htlc_failures = Vec::new();
1721                 let _ = self.total_consistency_lock.read().unwrap();
1722
1723                 {
1724                         let mut channel_lock = self.channel_state.lock().unwrap();
1725                         let channel_state = channel_lock.borrow_parts();
1726                         let short_to_id = channel_state.short_to_id;
1727                         let pending_msg_events = channel_state.pending_msg_events;
1728                         channel_state.by_id.retain(|_, channel| {
1729                                 if channel.is_awaiting_monitor_update() {
1730                                         let chan_monitor = channel.channel_monitor();
1731                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1732                                                 match e {
1733                                                         ChannelMonitorUpdateErr::PermanentFailure => {
1734                                                                 // TODO: There may be some pending HTLCs that we intended to fail
1735                                                                 // backwards when a monitor update failed. We should make sure
1736                                                                 // knowledge of those gets moved into the appropriate in-memory
1737                                                                 // ChannelMonitor and they get failed backwards once we get
1738                                                                 // on-chain confirmations.
1739                                                                 // Note I think #198 addresses this, so once its merged a test
1740                                                                 // should be written.
1741                                                                 if let Some(short_id) = channel.get_short_channel_id() {
1742                                                                         short_to_id.remove(&short_id);
1743                                                                 }
1744                                                                 close_results.push(channel.force_shutdown());
1745                                                                 if let Ok(update) = self.get_channel_update(&channel) {
1746                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1747                                                                                 msg: update
1748                                                                         });
1749                                                                 }
1750                                                                 false
1751                                                         },
1752                                                         ChannelMonitorUpdateErr::TemporaryFailure => true,
1753                                                 }
1754                                         } else {
1755                                                 let (raa, commitment_update, order, pending_forwards, mut pending_failures) = channel.monitor_updating_restored();
1756                                                 if !pending_forwards.is_empty() {
1757                                                         htlc_forwards.push((channel.get_short_channel_id().expect("We can't have pending forwards before funding confirmation"), pending_forwards));
1758                                                 }
1759                                                 htlc_failures.append(&mut pending_failures);
1760
1761                                                 macro_rules! handle_cs { () => {
1762                                                         if let Some(update) = commitment_update {
1763                                                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1764                                                                         node_id: channel.get_their_node_id(),
1765                                                                         updates: update,
1766                                                                 });
1767                                                         }
1768                                                 } }
1769                                                 macro_rules! handle_raa { () => {
1770                                                         if let Some(revoke_and_ack) = raa {
1771                                                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
1772                                                                         node_id: channel.get_their_node_id(),
1773                                                                         msg: revoke_and_ack,
1774                                                                 });
1775                                                         }
1776                                                 } }
1777                                                 match order {
1778                                                         RAACommitmentOrder::CommitmentFirst => {
1779                                                                 handle_cs!();
1780                                                                 handle_raa!();
1781                                                         },
1782                                                         RAACommitmentOrder::RevokeAndACKFirst => {
1783                                                                 handle_raa!();
1784                                                                 handle_cs!();
1785                                                         },
1786                                                 }
1787                                                 true
1788                                         }
1789                                 } else { true }
1790                         });
1791                 }
1792
1793                 for failure in htlc_failures.drain(..) {
1794                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
1795                 }
1796                 self.forward_htlcs(&mut htlc_forwards[..]);
1797
1798                 for res in close_results.drain(..) {
1799                         self.finish_force_close_channel(res);
1800                 }
1801         }
1802
1803         fn internal_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
1804                 if msg.chain_hash != self.genesis_hash {
1805                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash", msg.temporary_channel_id.clone()));
1806                 }
1807
1808                 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)
1809                         .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
1810                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1811                 let channel_state = channel_state_lock.borrow_parts();
1812                 match channel_state.by_id.entry(channel.channel_id()) {
1813                         hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!", msg.temporary_channel_id.clone())),
1814                         hash_map::Entry::Vacant(entry) => {
1815                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
1816                                         node_id: their_node_id.clone(),
1817                                         msg: channel.get_accept_channel(),
1818                                 });
1819                                 entry.insert(channel);
1820                         }
1821                 }
1822                 Ok(())
1823         }
1824
1825         fn internal_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
1826                 let (value, output_script, user_id) = {
1827                         let mut channel_lock = self.channel_state.lock().unwrap();
1828                         let channel_state = channel_lock.borrow_parts();
1829                         match channel_state.by_id.entry(msg.temporary_channel_id) {
1830                                 hash_map::Entry::Occupied(mut chan) => {
1831                                         if chan.get().get_their_node_id() != *their_node_id {
1832                                                 //TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
1833                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1834                                         }
1835                                         try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration), channel_state, chan);
1836                                         (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
1837                                 },
1838                                 //TODO: same as above
1839                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1840                         }
1841                 };
1842                 let mut pending_events = self.pending_events.lock().unwrap();
1843                 pending_events.push(events::Event::FundingGenerationReady {
1844                         temporary_channel_id: msg.temporary_channel_id,
1845                         channel_value_satoshis: value,
1846                         output_script: output_script,
1847                         user_channel_id: user_id,
1848                 });
1849                 Ok(())
1850         }
1851
1852         fn internal_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
1853                 let ((funding_msg, monitor_update), chan) = {
1854                         let mut channel_lock = self.channel_state.lock().unwrap();
1855                         let channel_state = channel_lock.borrow_parts();
1856                         match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
1857                                 hash_map::Entry::Occupied(mut chan) => {
1858                                         if chan.get().get_their_node_id() != *their_node_id {
1859                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1860                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1861                                         }
1862                                         (try_chan_entry!(self, chan.get_mut().funding_created(msg), channel_state, chan), chan.remove())
1863                                 },
1864                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1865                         }
1866                 };
1867                 // Because we have exclusive ownership of the channel here we can release the channel_state
1868                 // lock before add_update_monitor
1869                 if let Err(_e) = self.monitor.add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) {
1870                         unimplemented!();
1871                 }
1872                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1873                 let channel_state = channel_state_lock.borrow_parts();
1874                 match channel_state.by_id.entry(funding_msg.channel_id) {
1875                         hash_map::Entry::Occupied(_) => {
1876                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id", funding_msg.channel_id))
1877                         },
1878                         hash_map::Entry::Vacant(e) => {
1879                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
1880                                         node_id: their_node_id.clone(),
1881                                         msg: funding_msg,
1882                                 });
1883                                 e.insert(chan);
1884                         }
1885                 }
1886                 Ok(())
1887         }
1888
1889         fn internal_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
1890                 let (funding_txo, user_id) = {
1891                         let mut channel_lock = self.channel_state.lock().unwrap();
1892                         let channel_state = channel_lock.borrow_parts();
1893                         match channel_state.by_id.entry(msg.channel_id) {
1894                                 hash_map::Entry::Occupied(mut chan) => {
1895                                         if chan.get().get_their_node_id() != *their_node_id {
1896                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1897                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1898                                         }
1899                                         let chan_monitor = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
1900                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1901                                                 unimplemented!();
1902                                         }
1903                                         (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())
1904                                 },
1905                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1906                         }
1907                 };
1908                 let mut pending_events = self.pending_events.lock().unwrap();
1909                 pending_events.push(events::Event::FundingBroadcastSafe {
1910                         funding_txo: funding_txo,
1911                         user_channel_id: user_id,
1912                 });
1913                 Ok(())
1914         }
1915
1916         fn internal_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), MsgHandleErrInternal> {
1917                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1918                 let channel_state = channel_state_lock.borrow_parts();
1919                 match channel_state.by_id.entry(msg.channel_id) {
1920                         hash_map::Entry::Occupied(mut chan) => {
1921                                 if chan.get().get_their_node_id() != *their_node_id {
1922                                         //TODO: here and below MsgHandleErrInternal, #153 case
1923                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1924                                 }
1925                                 try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
1926                                 if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
1927                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
1928                                                 node_id: their_node_id.clone(),
1929                                                 msg: announcement_sigs,
1930                                         });
1931                                 }
1932                                 Ok(())
1933                         },
1934                         hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1935                 }
1936         }
1937
1938         fn internal_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
1939                 let (mut dropped_htlcs, chan_option) = {
1940                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1941                         let channel_state = channel_state_lock.borrow_parts();
1942
1943                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1944                                 hash_map::Entry::Occupied(mut chan_entry) => {
1945                                         if chan_entry.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                                         let (shutdown, closing_signed, dropped_htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg), channel_state, chan_entry);
1950                                         if let Some(msg) = shutdown {
1951                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
1952                                                         node_id: their_node_id.clone(),
1953                                                         msg,
1954                                                 });
1955                                         }
1956                                         if let Some(msg) = closing_signed {
1957                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1958                                                         node_id: their_node_id.clone(),
1959                                                         msg,
1960                                                 });
1961                                         }
1962                                         if chan_entry.get().is_shutdown() {
1963                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1964                                                         channel_state.short_to_id.remove(&short_id);
1965                                                 }
1966                                                 (dropped_htlcs, Some(chan_entry.remove_entry().1))
1967                                         } else { (dropped_htlcs, None) }
1968                                 },
1969                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1970                         }
1971                 };
1972                 for htlc_source in dropped_htlcs.drain(..) {
1973                         // unknown_next_peer...I dunno who that is anymore....
1974                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
1975                 }
1976                 if let Some(chan) = chan_option {
1977                         if let Ok(update) = self.get_channel_update(&chan) {
1978                                 let mut channel_state = self.channel_state.lock().unwrap();
1979                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1980                                         msg: update
1981                                 });
1982                         }
1983                 }
1984                 Ok(())
1985         }
1986
1987         fn internal_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
1988                 let (tx, chan_option) = {
1989                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1990                         let channel_state = channel_state_lock.borrow_parts();
1991                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1992                                 hash_map::Entry::Occupied(mut chan_entry) => {
1993                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1994                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1995                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1996                                         }
1997                                         let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg), channel_state, chan_entry);
1998                                         if let Some(msg) = closing_signed {
1999                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2000                                                         node_id: their_node_id.clone(),
2001                                                         msg,
2002                                                 });
2003                                         }
2004                                         if tx.is_some() {
2005                                                 // We're done with this channel, we've got a signed closing transaction and
2006                                                 // will send the closing_signed back to the remote peer upon return. This
2007                                                 // also implies there are no pending HTLCs left on the channel, so we can
2008                                                 // fully delete it from tracking (the channel monitor is still around to
2009                                                 // watch for old state broadcasts)!
2010                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2011                                                         channel_state.short_to_id.remove(&short_id);
2012                                                 }
2013                                                 (tx, Some(chan_entry.remove_entry().1))
2014                                         } else { (tx, None) }
2015                                 },
2016                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2017                         }
2018                 };
2019                 if let Some(broadcast_tx) = tx {
2020                         self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
2021                 }
2022                 if let Some(chan) = chan_option {
2023                         if let Ok(update) = self.get_channel_update(&chan) {
2024                                 let mut channel_state = self.channel_state.lock().unwrap();
2025                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2026                                         msg: update
2027                                 });
2028                         }
2029                 }
2030                 Ok(())
2031         }
2032
2033         fn internal_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
2034                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
2035                 //determine the state of the payment based on our response/if we forward anything/the time
2036                 //we take to respond. We should take care to avoid allowing such an attack.
2037                 //
2038                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
2039                 //us repeatedly garbled in different ways, and compare our error messages, which are
2040                 //encrypted with the same key. Its not immediately obvious how to usefully exploit that,
2041                 //but we should prevent it anyway.
2042
2043                 let (mut pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
2044                 let channel_state = channel_state_lock.borrow_parts();
2045
2046                 match channel_state.by_id.entry(msg.channel_id) {
2047                         hash_map::Entry::Occupied(mut chan) => {
2048                                 if chan.get().get_their_node_id() != *their_node_id {
2049                                         //TODO: here MsgHandleErrInternal, #153 case
2050                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2051                                 }
2052                                 if !chan.get().is_usable() {
2053                                         // If the update_add is completely bogus, the call will Err and we will close,
2054                                         // but if we've sent a shutdown and they haven't acknowledged it yet, we just
2055                                         // want to reject the new HTLC and fail it backwards instead of forwarding.
2056                                         if let PendingHTLCStatus::Forward(PendingForwardHTLCInfo { incoming_shared_secret, .. }) = pending_forward_info {
2057                                                 let chan_update = self.get_channel_update(chan.get());
2058                                                 pending_forward_info = PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
2059                                                         channel_id: msg.channel_id,
2060                                                         htlc_id: msg.htlc_id,
2061                                                         reason: if let Ok(update) = chan_update {
2062                                                                 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x1000|20, &update.encode_with_len()[..])
2063                                                         } else {
2064                                                                 // This can only happen if the channel isn't in the fully-funded
2065                                                                 // state yet, implying our counterparty is trying to route payments
2066                                                                 // over the channel back to themselves (cause no one else should
2067                                                                 // know the short_id is a lightning channel yet). We should have no
2068                                                                 // problem just calling this unknown_next_peer
2069                                                                 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x4000|10, &[])
2070                                                         },
2071                                                 }));
2072                                         }
2073                                 }
2074                                 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info), channel_state, chan);
2075                         },
2076                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2077                 }
2078                 Ok(())
2079         }
2080
2081         fn internal_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
2082                 let mut channel_lock = self.channel_state.lock().unwrap();
2083                 let htlc_source = {
2084                         let channel_state = channel_lock.borrow_parts();
2085                         match channel_state.by_id.entry(msg.channel_id) {
2086                                 hash_map::Entry::Occupied(mut chan) => {
2087                                         if chan.get().get_their_node_id() != *their_node_id {
2088                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2089                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2090                                         }
2091                                         try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), channel_state, chan)
2092                                 },
2093                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2094                         }
2095                 };
2096                 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
2097                 Ok(())
2098         }
2099
2100         // Process failure we got back from upstream on a payment we sent. Returns update and a boolean
2101         // indicating that the payment itself failed
2102         fn process_onion_failure(&self, htlc_source: &HTLCSource, mut packet_decrypted: Vec<u8>) -> (Option<msgs::HTLCFailChannelUpdate>, bool) {
2103                 if let &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } = htlc_source {
2104                         macro_rules! onion_failure_log {
2105                                 ( $error_code_textual: expr, $error_code: expr, $reported_name: expr, $reported_value: expr ) => {
2106                                         log_trace!(self, "{}({:#x}) {}({})", $error_code_textual, $error_code, $reported_name, $reported_value);
2107                                 };
2108                                 ( $error_code_textual: expr, $error_code: expr ) => {
2109                                         log_trace!(self, "{}({})", $error_code_textual, $error_code);
2110                                 };
2111                         }
2112
2113                         const BADONION: u16 = 0x8000;
2114                         const PERM: u16 = 0x4000;
2115                         const UPDATE: u16 = 0x1000;
2116
2117                         let mut res = None;
2118                         let mut htlc_msat = *first_hop_htlc_msat;
2119
2120                         // Handle packed channel/node updates for passing back for the route handler
2121                         Self::construct_onion_keys_callback(&self.secp_ctx, route, session_priv, |shared_secret, _, _, route_hop| {
2122                                 if res.is_some() { return; }
2123
2124                                 let incoming_htlc_msat = htlc_msat;
2125                                 let amt_to_forward = htlc_msat - route_hop.fee_msat;
2126                                 htlc_msat = amt_to_forward;
2127
2128                                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret[..]);
2129
2130                                 let mut decryption_tmp = Vec::with_capacity(packet_decrypted.len());
2131                                 decryption_tmp.resize(packet_decrypted.len(), 0);
2132                                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
2133                                 chacha.process(&packet_decrypted, &mut decryption_tmp[..]);
2134                                 packet_decrypted = decryption_tmp;
2135
2136                                 let is_from_final_node = route.hops.last().unwrap().pubkey == route_hop.pubkey;
2137
2138                                 if let Ok(err_packet) = msgs::DecodedOnionErrorPacket::read(&mut Cursor::new(&packet_decrypted)) {
2139                                         let um = ChannelManager::gen_um_from_shared_secret(&shared_secret[..]);
2140                                         let mut hmac = Hmac::new(Sha256::new(), &um);
2141                                         hmac.input(&err_packet.encode()[32..]);
2142                                         let mut calc_tag = [0u8; 32];
2143                                         hmac.raw_result(&mut calc_tag);
2144
2145                                         if crypto::util::fixed_time_eq(&calc_tag, &err_packet.hmac) {
2146                                                 if err_packet.failuremsg.len() < 2 {
2147                                                         // Useless packet that we can't use but it passed HMAC, so it
2148                                                         // definitely came from the peer in question
2149                                                         res = Some((None, !is_from_final_node));
2150                                                 } else {
2151                                                         let error_code = byte_utils::slice_to_be16(&err_packet.failuremsg[0..2]);
2152
2153                                                         match error_code & 0xff {
2154                                                                 1|2|3 => {
2155                                                                         // either from an intermediate or final node
2156                                                                         //   invalid_realm(PERM|1),
2157                                                                         //   temporary_node_failure(NODE|2)
2158                                                                         //   permanent_node_failure(PERM|NODE|2)
2159                                                                         //   required_node_feature_mssing(PERM|NODE|3)
2160                                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2161                                                                                 node_id: route_hop.pubkey,
2162                                                                                 is_permanent: error_code & PERM == PERM,
2163                                                                         }), !(error_code & PERM == PERM && is_from_final_node)));
2164                                                                         // node returning invalid_realm is removed from network_map,
2165                                                                         // although NODE flag is not set, TODO: or remove channel only?
2166                                                                         // retry payment when removed node is not a final node
2167                                                                         return;
2168                                                                 },
2169                                                                 _ => {}
2170                                                         }
2171
2172                                                         if is_from_final_node {
2173                                                                 let payment_retryable = match error_code {
2174                                                                         c if c == PERM|15 => false, // unknown_payment_hash
2175                                                                         c if c == PERM|16 => false, // incorrect_payment_amount
2176                                                                         17 => true, // final_expiry_too_soon
2177                                                                         18 if err_packet.failuremsg.len() == 6 => { // final_incorrect_cltv_expiry
2178                                                                                 let _reported_cltv_expiry = byte_utils::slice_to_be32(&err_packet.failuremsg[2..2+4]);
2179                                                                                 true
2180                                                                         },
2181                                                                         19 if err_packet.failuremsg.len() == 10 => { // final_incorrect_htlc_amount
2182                                                                                 let _reported_incoming_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
2183                                                                                 true
2184                                                                         },
2185                                                                         _ => {
2186                                                                                 // A final node has sent us either an invalid code or an error_code that
2187                                                                                 // MUST be sent from the processing node, or the formmat of failuremsg
2188                                                                                 // does not coform to the spec.
2189                                                                                 // Remove it from the network map and don't may retry payment
2190                                                                                 res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2191                                                                                         node_id: route_hop.pubkey,
2192                                                                                         is_permanent: true,
2193                                                                                 }), false));
2194                                                                                 return;
2195                                                                         }
2196                                                                 };
2197                                                                 res = Some((None, payment_retryable));
2198                                                                 return;
2199                                                         }
2200
2201                                                         // now, error_code should be only from the intermediate nodes
2202                                                         match error_code {
2203                                                                 _c if error_code & PERM == PERM => {
2204                                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
2205                                                                                 short_channel_id: route_hop.short_channel_id,
2206                                                                                 is_permanent: true,
2207                                                                         }), false));
2208                                                                 },
2209                                                                 _c if error_code & UPDATE == UPDATE => {
2210                                                                         let offset = match error_code {
2211                                                                                 c if c == UPDATE|7  => 0, // temporary_channel_failure
2212                                                                                 c if c == UPDATE|11 => 8, // amount_below_minimum
2213                                                                                 c if c == UPDATE|12 => 8, // fee_insufficient
2214                                                                                 c if c == UPDATE|13 => 4, // incorrect_cltv_expiry
2215                                                                                 c if c == UPDATE|14 => 0, // expiry_too_soon
2216                                                                                 c if c == UPDATE|20 => 2, // channel_disabled
2217                                                                                 _ =>  {
2218                                                                                         // node sending unknown code
2219                                                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2220                                                                                                 node_id: route_hop.pubkey,
2221                                                                                                 is_permanent: true,
2222                                                                                         }), false));
2223                                                                                         return;
2224                                                                                 }
2225                                                                         };
2226
2227                                                                         if err_packet.failuremsg.len() >= offset + 2 {
2228                                                                                 let update_len = byte_utils::slice_to_be16(&err_packet.failuremsg[offset+2..offset+4]) as usize;
2229                                                                                 if err_packet.failuremsg.len() >= offset + 4 + update_len {
2230                                                                                         if let Ok(chan_update) = msgs::ChannelUpdate::read(&mut Cursor::new(&err_packet.failuremsg[offset + 4..offset + 4 + update_len])) {
2231                                                                                                 // if channel_update should NOT have caused the failure:
2232                                                                                                 // MAY treat the channel_update as invalid.
2233                                                                                                 let is_chan_update_invalid = match error_code {
2234                                                                                                         c if c == UPDATE|7 => { // temporary_channel_failure
2235                                                                                                                 false
2236                                                                                                         },
2237                                                                                                         c if c == UPDATE|11 => { // amount_below_minimum
2238                                                                                                                 let reported_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
2239                                                                                                                 onion_failure_log!("amount_below_minimum", UPDATE|11, "htlc_msat", reported_htlc_msat);
2240                                                                                                                 incoming_htlc_msat > chan_update.contents.htlc_minimum_msat
2241                                                                                                         },
2242                                                                                                         c if c == UPDATE|12 => { // fee_insufficient
2243                                                                                                                 let reported_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
2244                                                                                                                 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) });
2245                                                                                                                 onion_failure_log!("fee_insufficient", UPDATE|12, "htlc_msat", reported_htlc_msat);
2246                                                                                                                 new_fee.is_none() || incoming_htlc_msat >= new_fee.unwrap() && incoming_htlc_msat >= amt_to_forward + new_fee.unwrap()
2247                                                                                                         }
2248                                                                                                         c if c == UPDATE|13 => { // incorrect_cltv_expiry
2249                                                                                                                 let reported_cltv_expiry = byte_utils::slice_to_be32(&err_packet.failuremsg[2..2+4]);
2250                                                                                                                 onion_failure_log!("incorrect_cltv_expiry", UPDATE|13, "cltv_expiry", reported_cltv_expiry);
2251                                                                                                                 route_hop.cltv_expiry_delta as u16 >= chan_update.contents.cltv_expiry_delta
2252                                                                                                         },
2253                                                                                                         c if c == UPDATE|20 => { // channel_disabled
2254                                                                                                                 let reported_flags = byte_utils::slice_to_be16(&err_packet.failuremsg[2..2+2]);
2255                                                                                                                 onion_failure_log!("channel_disabled", UPDATE|20, "flags", reported_flags);
2256                                                                                                                 chan_update.contents.flags & 0x01 == 0x01
2257                                                                                                         },
2258                                                                                                         c if c == UPDATE|21 => true, // expiry_too_far
2259                                                                                                         _ => { unreachable!(); },
2260                                                                                                 };
2261
2262                                                                                                 let msg = if is_chan_update_invalid { None } else {
2263                                                                                                         Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {
2264                                                                                                                 msg: chan_update,
2265                                                                                                         })
2266                                                                                                 };
2267                                                                                                 res = Some((msg, true));
2268                                                                                                 return;
2269                                                                                         }
2270                                                                                 }
2271                                                                         }
2272                                                                 },
2273                                                                 _c if error_code & BADONION == BADONION => {
2274                                                                         //TODO
2275                                                                 },
2276                                                                 14 => { // expiry_too_soon
2277                                                                         res = Some((None, true));
2278                                                                         return;
2279                                                                 }
2280                                                                 _ => {
2281                                                                         // node sending unknown code
2282                                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2283                                                                                 node_id: route_hop.pubkey,
2284                                                                                 is_permanent: true,
2285                                                                         }), false));
2286                                                                         return;
2287                                                                 }
2288                                                         }
2289                                                 }
2290                                         }
2291                                 }
2292                         }).expect("Route that we sent via spontaneously grew invalid keys in the middle of it?");
2293                         res.unwrap_or((None, true))
2294                 } else { ((None, true)) }
2295         }
2296
2297         fn internal_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
2298                 let mut channel_lock = self.channel_state.lock().unwrap();
2299                 let channel_state = channel_lock.borrow_parts();
2300                 match channel_state.by_id.entry(msg.channel_id) {
2301                         hash_map::Entry::Occupied(mut chan) => {
2302                                 if chan.get().get_their_node_id() != *their_node_id {
2303                                         //TODO: here and below MsgHandleErrInternal, #153 case
2304                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2305                                 }
2306                                 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::ErrorPacket { err: msg.reason.clone() }), channel_state, chan);
2307                         },
2308                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2309                 }
2310                 Ok(())
2311         }
2312
2313         fn internal_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
2314                 let mut channel_lock = self.channel_state.lock().unwrap();
2315                 let channel_state = channel_lock.borrow_parts();
2316                 match channel_state.by_id.entry(msg.channel_id) {
2317                         hash_map::Entry::Occupied(mut chan) => {
2318                                 if chan.get().get_their_node_id() != *their_node_id {
2319                                         //TODO: here and below MsgHandleErrInternal, #153 case
2320                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2321                                 }
2322                                 if (msg.failure_code & 0x8000) == 0 {
2323                                         try_chan_entry!(self, Err(ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set")), channel_state, chan);
2324                                 }
2325                                 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);
2326                                 Ok(())
2327                         },
2328                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2329                 }
2330         }
2331
2332         fn internal_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
2333                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2334                 let channel_state = channel_state_lock.borrow_parts();
2335                 match channel_state.by_id.entry(msg.channel_id) {
2336                         hash_map::Entry::Occupied(mut chan) => {
2337                                 if chan.get().get_their_node_id() != *their_node_id {
2338                                         //TODO: here and below MsgHandleErrInternal, #153 case
2339                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2340                                 }
2341                                 let (revoke_and_ack, commitment_signed, closing_signed, chan_monitor) =
2342                                         try_chan_entry!(self, chan.get_mut().commitment_signed(&msg, &*self.fee_estimator), channel_state, chan);
2343                                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2344                                         return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, commitment_signed.is_some());
2345                                         //TODO: Rebroadcast closing_signed if present on monitor update restoration
2346                                 }
2347                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2348                                         node_id: their_node_id.clone(),
2349                                         msg: revoke_and_ack,
2350                                 });
2351                                 if let Some(msg) = commitment_signed {
2352                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2353                                                 node_id: their_node_id.clone(),
2354                                                 updates: msgs::CommitmentUpdate {
2355                                                         update_add_htlcs: Vec::new(),
2356                                                         update_fulfill_htlcs: Vec::new(),
2357                                                         update_fail_htlcs: Vec::new(),
2358                                                         update_fail_malformed_htlcs: Vec::new(),
2359                                                         update_fee: None,
2360                                                         commitment_signed: msg,
2361                                                 },
2362                                         });
2363                                 }
2364                                 if let Some(msg) = closing_signed {
2365                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2366                                                 node_id: their_node_id.clone(),
2367                                                 msg,
2368                                         });
2369                                 }
2370                                 Ok(())
2371                         },
2372                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2373                 }
2374         }
2375
2376         #[inline]
2377         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64)>)]) {
2378                 for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
2379                         let mut forward_event = None;
2380                         if !pending_forwards.is_empty() {
2381                                 let mut channel_state = self.channel_state.lock().unwrap();
2382                                 if channel_state.forward_htlcs.is_empty() {
2383                                         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));
2384                                         channel_state.next_forward = forward_event.unwrap();
2385                                 }
2386                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2387                                         match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
2388                                                 hash_map::Entry::Occupied(mut entry) => {
2389                                                         entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info });
2390                                                 },
2391                                                 hash_map::Entry::Vacant(entry) => {
2392                                                         entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info }));
2393                                                 }
2394                                         }
2395                                 }
2396                         }
2397                         match forward_event {
2398                                 Some(time) => {
2399                                         let mut pending_events = self.pending_events.lock().unwrap();
2400                                         pending_events.push(events::Event::PendingHTLCsForwardable {
2401                                                 time_forwardable: time
2402                                         });
2403                                 }
2404                                 None => {},
2405                         }
2406                 }
2407         }
2408
2409         fn internal_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
2410                 let (pending_forwards, mut pending_failures, short_channel_id) = {
2411                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2412                         let channel_state = channel_state_lock.borrow_parts();
2413                         match channel_state.by_id.entry(msg.channel_id) {
2414                                 hash_map::Entry::Occupied(mut chan) => {
2415                                         if chan.get().get_their_node_id() != *their_node_id {
2416                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2417                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2418                                         }
2419                                         let (commitment_update, pending_forwards, pending_failures, closing_signed, chan_monitor) =
2420                                                 try_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &*self.fee_estimator), channel_state, chan);
2421                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2422                                                 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, pending_forwards, pending_failures);
2423                                         }
2424                                         if let Some(updates) = commitment_update {
2425                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2426                                                         node_id: their_node_id.clone(),
2427                                                         updates,
2428                                                 });
2429                                         }
2430                                         if let Some(msg) = closing_signed {
2431                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2432                                                         node_id: their_node_id.clone(),
2433                                                         msg,
2434                                                 });
2435                                         }
2436                                         (pending_forwards, pending_failures, chan.get().get_short_channel_id().expect("RAA should only work on a short-id-available channel"))
2437                                 },
2438                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2439                         }
2440                 };
2441                 for failure in pending_failures.drain(..) {
2442                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2443                 }
2444                 self.forward_htlcs(&mut [(short_channel_id, pending_forwards)]);
2445
2446                 Ok(())
2447         }
2448
2449         fn internal_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2450                 let mut channel_lock = self.channel_state.lock().unwrap();
2451                 let channel_state = channel_lock.borrow_parts();
2452                 match channel_state.by_id.entry(msg.channel_id) {
2453                         hash_map::Entry::Occupied(mut chan) => {
2454                                 if chan.get().get_their_node_id() != *their_node_id {
2455                                         //TODO: here and below MsgHandleErrInternal, #153 case
2456                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2457                                 }
2458                                 try_chan_entry!(self, chan.get_mut().update_fee(&*self.fee_estimator, &msg), channel_state, chan);
2459                         },
2460                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2461                 }
2462                 Ok(())
2463         }
2464
2465         fn internal_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2466                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2467                 let channel_state = channel_state_lock.borrow_parts();
2468
2469                 match channel_state.by_id.entry(msg.channel_id) {
2470                         hash_map::Entry::Occupied(mut chan) => {
2471                                 if chan.get().get_their_node_id() != *their_node_id {
2472                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2473                                 }
2474                                 if !chan.get().is_usable() {
2475                                         return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Got an announcement_signatures before we were ready for it", action: Some(msgs::ErrorAction::IgnoreError)}));
2476                                 }
2477
2478                                 let our_node_id = self.get_our_node_id();
2479                                 let (announcement, our_bitcoin_sig) =
2480                                         try_chan_entry!(self, chan.get_mut().get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone()), channel_state, chan);
2481
2482                                 let were_node_one = announcement.node_id_1 == our_node_id;
2483                                 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
2484                                 if self.secp_ctx.verify(&msghash, &msg.node_signature, if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 }).is_err() ||
2485                                                 self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 }).is_err() {
2486                                         try_chan_entry!(self, Err(ChannelError::Close("Bad announcement_signatures node_signature")), channel_state, chan);
2487                                 }
2488
2489                                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2490
2491                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
2492                                         msg: msgs::ChannelAnnouncement {
2493                                                 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
2494                                                 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
2495                                                 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
2496                                                 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
2497                                                 contents: announcement,
2498                                         },
2499                                         update_msg: self.get_channel_update(chan.get()).unwrap(), // can only fail if we're not in a ready state
2500                                 });
2501                         },
2502                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2503                 }
2504                 Ok(())
2505         }
2506
2507         fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
2508                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2509                 let channel_state = channel_state_lock.borrow_parts();
2510
2511                 match channel_state.by_id.entry(msg.channel_id) {
2512                         hash_map::Entry::Occupied(mut chan) => {
2513                                 if chan.get().get_their_node_id() != *their_node_id {
2514                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2515                                 }
2516                                 let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, mut order, shutdown) =
2517                                         try_chan_entry!(self, chan.get_mut().channel_reestablish(msg), channel_state, chan);
2518                                 if let Some(monitor) = channel_monitor {
2519                                         if let Err(e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
2520                                                 // channel_reestablish doesn't guarantee the order it returns is sensical
2521                                                 // for the messages it returns, but if we're setting what messages to
2522                                                 // re-transmit on monitor update success, we need to make sure it is sane.
2523                                                 if revoke_and_ack.is_none() {
2524                                                         order = RAACommitmentOrder::CommitmentFirst;
2525                                                 }
2526                                                 if commitment_update.is_none() {
2527                                                         order = RAACommitmentOrder::RevokeAndACKFirst;
2528                                                 }
2529                                                 return_monitor_err!(self, e, channel_state, chan, order);
2530                                                 //TODO: Resend the funding_locked if needed once we get the monitor running again
2531                                         }
2532                                 }
2533                                 if let Some(msg) = funding_locked {
2534                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2535                                                 node_id: their_node_id.clone(),
2536                                                 msg
2537                                         });
2538                                 }
2539                                 macro_rules! send_raa { () => {
2540                                         if let Some(msg) = revoke_and_ack {
2541                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2542                                                         node_id: their_node_id.clone(),
2543                                                         msg
2544                                                 });
2545                                         }
2546                                 } }
2547                                 macro_rules! send_cu { () => {
2548                                         if let Some(updates) = commitment_update {
2549                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2550                                                         node_id: their_node_id.clone(),
2551                                                         updates
2552                                                 });
2553                                         }
2554                                 } }
2555                                 match order {
2556                                         RAACommitmentOrder::RevokeAndACKFirst => {
2557                                                 send_raa!();
2558                                                 send_cu!();
2559                                         },
2560                                         RAACommitmentOrder::CommitmentFirst => {
2561                                                 send_cu!();
2562                                                 send_raa!();
2563                                         },
2564                                 }
2565                                 if let Some(msg) = shutdown {
2566                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2567                                                 node_id: their_node_id.clone(),
2568                                                 msg,
2569                                         });
2570                                 }
2571                                 Ok(())
2572                         },
2573                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2574                 }
2575         }
2576
2577         /// Begin Update fee process. Allowed only on an outbound channel.
2578         /// If successful, will generate a UpdateHTLCs event, so you should probably poll
2579         /// PeerManager::process_events afterwards.
2580         /// Note: This API is likely to change!
2581         #[doc(hidden)]
2582         pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u64) -> Result<(), APIError> {
2583                 let _ = self.total_consistency_lock.read().unwrap();
2584                 let their_node_id;
2585                 let err: Result<(), _> = loop {
2586                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2587                         let channel_state = channel_state_lock.borrow_parts();
2588
2589                         match channel_state.by_id.entry(channel_id) {
2590                                 hash_map::Entry::Vacant(_) => return Err(APIError::APIMisuseError{err: "Failed to find corresponding channel"}),
2591                                 hash_map::Entry::Occupied(mut chan) => {
2592                                         if !chan.get().is_outbound() {
2593                                                 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel"});
2594                                         }
2595                                         if chan.get().is_awaiting_monitor_update() {
2596                                                 return Err(APIError::MonitorUpdateFailed);
2597                                         }
2598                                         if !chan.get().is_live() {
2599                                                 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected"});
2600                                         }
2601                                         their_node_id = chan.get().get_their_node_id();
2602                                         if let Some((update_fee, commitment_signed, chan_monitor)) =
2603                                                         break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw), channel_state, chan)
2604                                         {
2605                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2606                                                         unimplemented!();
2607                                                 }
2608                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2609                                                         node_id: chan.get().get_their_node_id(),
2610                                                         updates: msgs::CommitmentUpdate {
2611                                                                 update_add_htlcs: Vec::new(),
2612                                                                 update_fulfill_htlcs: Vec::new(),
2613                                                                 update_fail_htlcs: Vec::new(),
2614                                                                 update_fail_malformed_htlcs: Vec::new(),
2615                                                                 update_fee: Some(update_fee),
2616                                                                 commitment_signed,
2617                                                         },
2618                                                 });
2619                                         }
2620                                 },
2621                         }
2622                         return Ok(())
2623                 };
2624
2625                 match handle_error!(self, err, their_node_id) {
2626                         Ok(_) => unreachable!(),
2627                         Err(e) => {
2628                                 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
2629                                 } else {
2630                                         log_error!(self, "Got bad keys: {}!", e.err);
2631                                         let mut channel_state = self.channel_state.lock().unwrap();
2632                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
2633                                                 node_id: their_node_id,
2634                                                 action: e.action,
2635                                         });
2636                                 }
2637                                 Err(APIError::APIMisuseError { err: e.err })
2638                         },
2639                 }
2640         }
2641 }
2642
2643 impl events::MessageSendEventsProvider for ChannelManager {
2644         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
2645                 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2646                 // user to serialize a ChannelManager with pending events in it and lose those events on
2647                 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2648                 {
2649                         //TODO: This behavior should be documented.
2650                         for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2651                                 if let Some(preimage) = htlc_update.payment_preimage {
2652                                         log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2653                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2654                                 } else {
2655                                         log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2656                                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
2657                                 }
2658                         }
2659                 }
2660
2661                 let mut ret = Vec::new();
2662                 let mut channel_state = self.channel_state.lock().unwrap();
2663                 mem::swap(&mut ret, &mut channel_state.pending_msg_events);
2664                 ret
2665         }
2666 }
2667
2668 impl events::EventsProvider for ChannelManager {
2669         fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
2670                 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2671                 // user to serialize a ChannelManager with pending events in it and lose those events on
2672                 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2673                 {
2674                         //TODO: This behavior should be documented.
2675                         for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2676                                 if let Some(preimage) = htlc_update.payment_preimage {
2677                                         log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2678                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2679                                 } else {
2680                                         log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2681                                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
2682                                 }
2683                         }
2684                 }
2685
2686                 let mut ret = Vec::new();
2687                 let mut pending_events = self.pending_events.lock().unwrap();
2688                 mem::swap(&mut ret, &mut *pending_events);
2689                 ret
2690         }
2691 }
2692
2693 impl ChainListener for ChannelManager {
2694         fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
2695                 let header_hash = header.bitcoin_hash();
2696                 log_trace!(self, "Block {} at height {} connected with {} txn matched", header_hash, height, txn_matched.len());
2697                 let _ = self.total_consistency_lock.read().unwrap();
2698                 let mut failed_channels = Vec::new();
2699                 {
2700                         let mut channel_lock = self.channel_state.lock().unwrap();
2701                         let channel_state = channel_lock.borrow_parts();
2702                         let short_to_id = channel_state.short_to_id;
2703                         let pending_msg_events = channel_state.pending_msg_events;
2704                         channel_state.by_id.retain(|_, channel| {
2705                                 let chan_res = channel.block_connected(header, height, txn_matched, indexes_of_txn_matched);
2706                                 if let Ok(Some(funding_locked)) = chan_res {
2707                                         pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2708                                                 node_id: channel.get_their_node_id(),
2709                                                 msg: funding_locked,
2710                                         });
2711                                         if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
2712                                                 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2713                                                         node_id: channel.get_their_node_id(),
2714                                                         msg: announcement_sigs,
2715                                                 });
2716                                         }
2717                                         short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
2718                                 } else if let Err(e) = chan_res {
2719                                         pending_msg_events.push(events::MessageSendEvent::HandleError {
2720                                                 node_id: channel.get_their_node_id(),
2721                                                 action: Some(msgs::ErrorAction::SendErrorMessage { msg: e }),
2722                                         });
2723                                         return false;
2724                                 }
2725                                 if let Some(funding_txo) = channel.get_funding_txo() {
2726                                         for tx in txn_matched {
2727                                                 for inp in tx.input.iter() {
2728                                                         if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
2729                                                                 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()));
2730                                                                 if let Some(short_id) = channel.get_short_channel_id() {
2731                                                                         short_to_id.remove(&short_id);
2732                                                                 }
2733                                                                 // It looks like our counterparty went on-chain. We go ahead and
2734                                                                 // broadcast our latest local state as well here, just in case its
2735                                                                 // some kind of SPV attack, though we expect these to be dropped.
2736                                                                 failed_channels.push(channel.force_shutdown());
2737                                                                 if let Ok(update) = self.get_channel_update(&channel) {
2738                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2739                                                                                 msg: update
2740                                                                         });
2741                                                                 }
2742                                                                 return false;
2743                                                         }
2744                                                 }
2745                                         }
2746                                 }
2747                                 if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height) {
2748                                         if let Some(short_id) = channel.get_short_channel_id() {
2749                                                 short_to_id.remove(&short_id);
2750                                         }
2751                                         failed_channels.push(channel.force_shutdown());
2752                                         // If would_broadcast_at_height() is true, the channel_monitor will broadcast
2753                                         // the latest local tx for us, so we should skip that here (it doesn't really
2754                                         // hurt anything, but does make tests a bit simpler).
2755                                         failed_channels.last_mut().unwrap().0 = Vec::new();
2756                                         if let Ok(update) = self.get_channel_update(&channel) {
2757                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2758                                                         msg: update
2759                                                 });
2760                                         }
2761                                         return false;
2762                                 }
2763                                 true
2764                         });
2765                 }
2766                 for failure in failed_channels.drain(..) {
2767                         self.finish_force_close_channel(failure);
2768                 }
2769                 self.latest_block_height.store(height as usize, Ordering::Release);
2770                 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header_hash;
2771         }
2772
2773         /// We force-close the channel without letting our counterparty participate in the shutdown
2774         fn block_disconnected(&self, header: &BlockHeader) {
2775                 let _ = self.total_consistency_lock.read().unwrap();
2776                 let mut failed_channels = Vec::new();
2777                 {
2778                         let mut channel_lock = self.channel_state.lock().unwrap();
2779                         let channel_state = channel_lock.borrow_parts();
2780                         let short_to_id = channel_state.short_to_id;
2781                         let pending_msg_events = channel_state.pending_msg_events;
2782                         channel_state.by_id.retain(|_,  v| {
2783                                 if v.block_disconnected(header) {
2784                                         if let Some(short_id) = v.get_short_channel_id() {
2785                                                 short_to_id.remove(&short_id);
2786                                         }
2787                                         failed_channels.push(v.force_shutdown());
2788                                         if let Ok(update) = self.get_channel_update(&v) {
2789                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2790                                                         msg: update
2791                                                 });
2792                                         }
2793                                         false
2794                                 } else {
2795                                         true
2796                                 }
2797                         });
2798                 }
2799                 for failure in failed_channels.drain(..) {
2800                         self.finish_force_close_channel(failure);
2801                 }
2802                 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
2803                 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
2804         }
2805 }
2806
2807 impl ChannelMessageHandler for ChannelManager {
2808         //TODO: Handle errors and close channel (or so)
2809         fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), HandleError> {
2810                 let _ = self.total_consistency_lock.read().unwrap();
2811                 handle_error!(self, self.internal_open_channel(their_node_id, msg), their_node_id)
2812         }
2813
2814         fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), HandleError> {
2815                 let _ = self.total_consistency_lock.read().unwrap();
2816                 handle_error!(self, self.internal_accept_channel(their_node_id, msg), their_node_id)
2817         }
2818
2819         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), HandleError> {
2820                 let _ = self.total_consistency_lock.read().unwrap();
2821                 handle_error!(self, self.internal_funding_created(their_node_id, msg), their_node_id)
2822         }
2823
2824         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), HandleError> {
2825                 let _ = self.total_consistency_lock.read().unwrap();
2826                 handle_error!(self, self.internal_funding_signed(their_node_id, msg), their_node_id)
2827         }
2828
2829         fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), HandleError> {
2830                 let _ = self.total_consistency_lock.read().unwrap();
2831                 handle_error!(self, self.internal_funding_locked(their_node_id, msg), their_node_id)
2832         }
2833
2834         fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), HandleError> {
2835                 let _ = self.total_consistency_lock.read().unwrap();
2836                 handle_error!(self, self.internal_shutdown(their_node_id, msg), their_node_id)
2837         }
2838
2839         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), HandleError> {
2840                 let _ = self.total_consistency_lock.read().unwrap();
2841                 handle_error!(self, self.internal_closing_signed(their_node_id, msg), their_node_id)
2842         }
2843
2844         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), msgs::HandleError> {
2845                 let _ = self.total_consistency_lock.read().unwrap();
2846                 handle_error!(self, self.internal_update_add_htlc(their_node_id, msg), their_node_id)
2847         }
2848
2849         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), HandleError> {
2850                 let _ = self.total_consistency_lock.read().unwrap();
2851                 handle_error!(self, self.internal_update_fulfill_htlc(their_node_id, msg), their_node_id)
2852         }
2853
2854         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), HandleError> {
2855                 let _ = self.total_consistency_lock.read().unwrap();
2856                 handle_error!(self, self.internal_update_fail_htlc(their_node_id, msg), their_node_id)
2857         }
2858
2859         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), HandleError> {
2860                 let _ = self.total_consistency_lock.read().unwrap();
2861                 handle_error!(self, self.internal_update_fail_malformed_htlc(their_node_id, msg), their_node_id)
2862         }
2863
2864         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), HandleError> {
2865                 let _ = self.total_consistency_lock.read().unwrap();
2866                 handle_error!(self, self.internal_commitment_signed(their_node_id, msg), their_node_id)
2867         }
2868
2869         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), HandleError> {
2870                 let _ = self.total_consistency_lock.read().unwrap();
2871                 handle_error!(self, self.internal_revoke_and_ack(their_node_id, msg), their_node_id)
2872         }
2873
2874         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), HandleError> {
2875                 let _ = self.total_consistency_lock.read().unwrap();
2876                 handle_error!(self, self.internal_update_fee(their_node_id, msg), their_node_id)
2877         }
2878
2879         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), HandleError> {
2880                 let _ = self.total_consistency_lock.read().unwrap();
2881                 handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
2882         }
2883
2884         fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), HandleError> {
2885                 let _ = self.total_consistency_lock.read().unwrap();
2886                 handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), their_node_id)
2887         }
2888
2889         fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
2890                 let _ = self.total_consistency_lock.read().unwrap();
2891                 let mut failed_channels = Vec::new();
2892                 let mut failed_payments = Vec::new();
2893                 {
2894                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2895                         let channel_state = channel_state_lock.borrow_parts();
2896                         let short_to_id = channel_state.short_to_id;
2897                         let pending_msg_events = channel_state.pending_msg_events;
2898                         if no_connection_possible {
2899                                 log_debug!(self, "Failing all channels with {} due to no_connection_possible", log_pubkey!(their_node_id));
2900                                 channel_state.by_id.retain(|_, chan| {
2901                                         if chan.get_their_node_id() == *their_node_id {
2902                                                 if let Some(short_id) = chan.get_short_channel_id() {
2903                                                         short_to_id.remove(&short_id);
2904                                                 }
2905                                                 failed_channels.push(chan.force_shutdown());
2906                                                 if let Ok(update) = self.get_channel_update(&chan) {
2907                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2908                                                                 msg: update
2909                                                         });
2910                                                 }
2911                                                 false
2912                                         } else {
2913                                                 true
2914                                         }
2915                                 });
2916                         } else {
2917                                 log_debug!(self, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(their_node_id));
2918                                 channel_state.by_id.retain(|_, chan| {
2919                                         if chan.get_their_node_id() == *their_node_id {
2920                                                 //TODO: mark channel disabled (and maybe announce such after a timeout).
2921                                                 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused();
2922                                                 if !failed_adds.is_empty() {
2923                                                         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
2924                                                         failed_payments.push((chan_update, failed_adds));
2925                                                 }
2926                                                 if chan.is_shutdown() {
2927                                                         if let Some(short_id) = chan.get_short_channel_id() {
2928                                                                 short_to_id.remove(&short_id);
2929                                                         }
2930                                                         return false;
2931                                                 }
2932                                         }
2933                                         true
2934                                 })
2935                         }
2936                 }
2937                 for failure in failed_channels.drain(..) {
2938                         self.finish_force_close_channel(failure);
2939                 }
2940                 for (chan_update, mut htlc_sources) in failed_payments {
2941                         for (htlc_source, payment_hash) in htlc_sources.drain(..) {
2942                                 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
2943                         }
2944                 }
2945         }
2946
2947         fn peer_connected(&self, their_node_id: &PublicKey) {
2948                 log_debug!(self, "Generating channel_reestablish events for {}", log_pubkey!(their_node_id));
2949
2950                 let _ = self.total_consistency_lock.read().unwrap();
2951                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2952                 let channel_state = channel_state_lock.borrow_parts();
2953                 let pending_msg_events = channel_state.pending_msg_events;
2954                 channel_state.by_id.retain(|_, chan| {
2955                         if chan.get_their_node_id() == *their_node_id {
2956                                 if !chan.have_received_message() {
2957                                         // If we created this (outbound) channel while we were disconnected from the
2958                                         // peer we probably failed to send the open_channel message, which is now
2959                                         // lost. We can't have had anything pending related to this channel, so we just
2960                                         // drop it.
2961                                         false
2962                                 } else {
2963                                         pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
2964                                                 node_id: chan.get_their_node_id(),
2965                                                 msg: chan.get_channel_reestablish(),
2966                                         });
2967                                         true
2968                                 }
2969                         } else { true }
2970                 });
2971                 //TODO: Also re-broadcast announcement_signatures
2972         }
2973
2974         fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
2975                 let _ = self.total_consistency_lock.read().unwrap();
2976
2977                 if msg.channel_id == [0; 32] {
2978                         for chan in self.list_channels() {
2979                                 if chan.remote_network_id == *their_node_id {
2980                                         self.force_close_channel(&chan.channel_id);
2981                                 }
2982                         }
2983                 } else {
2984                         self.force_close_channel(&msg.channel_id);
2985                 }
2986         }
2987 }
2988
2989 const SERIALIZATION_VERSION: u8 = 1;
2990 const MIN_SERIALIZATION_VERSION: u8 = 1;
2991
2992 impl Writeable for PendingForwardHTLCInfo {
2993         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2994                 if let &Some(ref onion) = &self.onion_packet {
2995                         1u8.write(writer)?;
2996                         onion.write(writer)?;
2997                 } else {
2998                         0u8.write(writer)?;
2999                 }
3000                 self.incoming_shared_secret.write(writer)?;
3001                 self.payment_hash.write(writer)?;
3002                 self.short_channel_id.write(writer)?;
3003                 self.amt_to_forward.write(writer)?;
3004                 self.outgoing_cltv_value.write(writer)?;
3005                 Ok(())
3006         }
3007 }
3008
3009 impl<R: ::std::io::Read> Readable<R> for PendingForwardHTLCInfo {
3010         fn read(reader: &mut R) -> Result<PendingForwardHTLCInfo, DecodeError> {
3011                 let onion_packet = match <u8 as Readable<R>>::read(reader)? {
3012                         0 => None,
3013                         1 => Some(msgs::OnionPacket::read(reader)?),
3014                         _ => return Err(DecodeError::InvalidValue),
3015                 };
3016                 Ok(PendingForwardHTLCInfo {
3017                         onion_packet,
3018                         incoming_shared_secret: Readable::read(reader)?,
3019                         payment_hash: Readable::read(reader)?,
3020                         short_channel_id: Readable::read(reader)?,
3021                         amt_to_forward: Readable::read(reader)?,
3022                         outgoing_cltv_value: Readable::read(reader)?,
3023                 })
3024         }
3025 }
3026
3027 impl Writeable for HTLCFailureMsg {
3028         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3029                 match self {
3030                         &HTLCFailureMsg::Relay(ref fail_msg) => {
3031                                 0u8.write(writer)?;
3032                                 fail_msg.write(writer)?;
3033                         },
3034                         &HTLCFailureMsg::Malformed(ref fail_msg) => {
3035                                 1u8.write(writer)?;
3036                                 fail_msg.write(writer)?;
3037                         }
3038                 }
3039                 Ok(())
3040         }
3041 }
3042
3043 impl<R: ::std::io::Read> Readable<R> for HTLCFailureMsg {
3044         fn read(reader: &mut R) -> Result<HTLCFailureMsg, DecodeError> {
3045                 match <u8 as Readable<R>>::read(reader)? {
3046                         0 => Ok(HTLCFailureMsg::Relay(Readable::read(reader)?)),
3047                         1 => Ok(HTLCFailureMsg::Malformed(Readable::read(reader)?)),
3048                         _ => Err(DecodeError::InvalidValue),
3049                 }
3050         }
3051 }
3052
3053 impl Writeable for PendingHTLCStatus {
3054         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3055                 match self {
3056                         &PendingHTLCStatus::Forward(ref forward_info) => {
3057                                 0u8.write(writer)?;
3058                                 forward_info.write(writer)?;
3059                         },
3060                         &PendingHTLCStatus::Fail(ref fail_msg) => {
3061                                 1u8.write(writer)?;
3062                                 fail_msg.write(writer)?;
3063                         }
3064                 }
3065                 Ok(())
3066         }
3067 }
3068
3069 impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
3070         fn read(reader: &mut R) -> Result<PendingHTLCStatus, DecodeError> {
3071                 match <u8 as Readable<R>>::read(reader)? {
3072                         0 => Ok(PendingHTLCStatus::Forward(Readable::read(reader)?)),
3073                         1 => Ok(PendingHTLCStatus::Fail(Readable::read(reader)?)),
3074                         _ => Err(DecodeError::InvalidValue),
3075                 }
3076         }
3077 }
3078
3079 impl_writeable!(HTLCPreviousHopData, 0, {
3080         short_channel_id,
3081         htlc_id,
3082         incoming_packet_shared_secret
3083 });
3084
3085 impl Writeable for HTLCSource {
3086         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3087                 match self {
3088                         &HTLCSource::PreviousHopData(ref hop_data) => {
3089                                 0u8.write(writer)?;
3090                                 hop_data.write(writer)?;
3091                         },
3092                         &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } => {
3093                                 1u8.write(writer)?;
3094                                 route.write(writer)?;
3095                                 session_priv.write(writer)?;
3096                                 first_hop_htlc_msat.write(writer)?;
3097                         }
3098                 }
3099                 Ok(())
3100         }
3101 }
3102
3103 impl<R: ::std::io::Read> Readable<R> for HTLCSource {
3104         fn read(reader: &mut R) -> Result<HTLCSource, DecodeError> {
3105                 match <u8 as Readable<R>>::read(reader)? {
3106                         0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
3107                         1 => Ok(HTLCSource::OutboundRoute {
3108                                 route: Readable::read(reader)?,
3109                                 session_priv: Readable::read(reader)?,
3110                                 first_hop_htlc_msat: Readable::read(reader)?,
3111                         }),
3112                         _ => Err(DecodeError::InvalidValue),
3113                 }
3114         }
3115 }
3116
3117 impl Writeable for HTLCFailReason {
3118         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3119                 match self {
3120                         &HTLCFailReason::ErrorPacket { ref err } => {
3121                                 0u8.write(writer)?;
3122                                 err.write(writer)?;
3123                         },
3124                         &HTLCFailReason::Reason { ref failure_code, ref data } => {
3125                                 1u8.write(writer)?;
3126                                 failure_code.write(writer)?;
3127                                 data.write(writer)?;
3128                         }
3129                 }
3130                 Ok(())
3131         }
3132 }
3133
3134 impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
3135         fn read(reader: &mut R) -> Result<HTLCFailReason, DecodeError> {
3136                 match <u8 as Readable<R>>::read(reader)? {
3137                         0 => Ok(HTLCFailReason::ErrorPacket { err: Readable::read(reader)? }),
3138                         1 => Ok(HTLCFailReason::Reason {
3139                                 failure_code: Readable::read(reader)?,
3140                                 data: Readable::read(reader)?,
3141                         }),
3142                         _ => Err(DecodeError::InvalidValue),
3143                 }
3144         }
3145 }
3146
3147 impl_writeable!(HTLCForwardInfo, 0, {
3148         prev_short_channel_id,
3149         prev_htlc_id,
3150         forward_info
3151 });
3152
3153 impl Writeable for ChannelManager {
3154         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3155                 let _ = self.total_consistency_lock.write().unwrap();
3156
3157                 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
3158                 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
3159
3160                 self.genesis_hash.write(writer)?;
3161                 (self.latest_block_height.load(Ordering::Acquire) as u32).write(writer)?;
3162                 self.last_block_hash.lock().unwrap().write(writer)?;
3163
3164                 let channel_state = self.channel_state.lock().unwrap();
3165                 let mut unfunded_channels = 0;
3166                 for (_, channel) in channel_state.by_id.iter() {
3167                         if !channel.is_funding_initiated() {
3168                                 unfunded_channels += 1;
3169                         }
3170                 }
3171                 ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
3172                 for (_, channel) in channel_state.by_id.iter() {
3173                         if channel.is_funding_initiated() {
3174                                 channel.write(writer)?;
3175                         }
3176                 }
3177
3178                 (channel_state.forward_htlcs.len() as u64).write(writer)?;
3179                 for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
3180                         short_channel_id.write(writer)?;
3181                         (pending_forwards.len() as u64).write(writer)?;
3182                         for forward in pending_forwards {
3183                                 forward.write(writer)?;
3184                         }
3185                 }
3186
3187                 (channel_state.claimable_htlcs.len() as u64).write(writer)?;
3188                 for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
3189                         payment_hash.write(writer)?;
3190                         (previous_hops.len() as u64).write(writer)?;
3191                         for previous_hop in previous_hops {
3192                                 previous_hop.write(writer)?;
3193                         }
3194                 }
3195
3196                 Ok(())
3197         }
3198 }
3199
3200 /// Arguments for the creation of a ChannelManager that are not deserialized.
3201 ///
3202 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
3203 /// is:
3204 /// 1) Deserialize all stored ChannelMonitors.
3205 /// 2) Deserialize the ChannelManager by filling in this struct and calling <(Sha256dHash,
3206 ///    ChannelManager)>::read(reader, args).
3207 ///    This may result in closing some Channels if the ChannelMonitor is newer than the stored
3208 ///    ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
3209 /// 3) Register all relevant ChannelMonitor outpoints with your chain watch mechanism using
3210 ///    ChannelMonitor::get_monitored_outpoints and ChannelMonitor::get_funding_txo().
3211 /// 4) Reconnect blocks on your ChannelMonitors.
3212 /// 5) Move the ChannelMonitors into your local ManyChannelMonitor.
3213 /// 6) Disconnect/connect blocks on the ChannelManager.
3214 /// 7) Register the new ChannelManager with your ChainWatchInterface (this does not happen
3215 ///    automatically as it does in ChannelManager::new()).
3216 pub struct ChannelManagerReadArgs<'a> {
3217         /// The keys provider which will give us relevant keys. Some keys will be loaded during
3218         /// deserialization.
3219         pub keys_manager: Arc<KeysInterface>,
3220
3221         /// The fee_estimator for use in the ChannelManager in the future.
3222         ///
3223         /// No calls to the FeeEstimator will be made during deserialization.
3224         pub fee_estimator: Arc<FeeEstimator>,
3225         /// The ManyChannelMonitor for use in the ChannelManager in the future.
3226         ///
3227         /// No calls to the ManyChannelMonitor will be made during deserialization. It is assumed that
3228         /// you have deserialized ChannelMonitors separately and will add them to your
3229         /// ManyChannelMonitor after deserializing this ChannelManager.
3230         pub monitor: Arc<ManyChannelMonitor>,
3231         /// The ChainWatchInterface for use in the ChannelManager in the future.
3232         ///
3233         /// No calls to the ChainWatchInterface will be made during deserialization.
3234         pub chain_monitor: Arc<ChainWatchInterface>,
3235         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
3236         /// used to broadcast the latest local commitment transactions of channels which must be
3237         /// force-closed during deserialization.
3238         pub tx_broadcaster: Arc<BroadcasterInterface>,
3239         /// The Logger for use in the ChannelManager and which may be used to log information during
3240         /// deserialization.
3241         pub logger: Arc<Logger>,
3242         /// Default settings used for new channels. Any existing channels will continue to use the
3243         /// runtime settings which were stored when the ChannelManager was serialized.
3244         pub default_config: UserConfig,
3245
3246         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
3247         /// value.get_funding_txo() should be the key).
3248         ///
3249         /// If a monitor is inconsistent with the channel state during deserialization the channel will
3250         /// be force-closed using the data in the channelmonitor and the Channel will be dropped. This
3251         /// is true for missing channels as well. If there is a monitor missing for which we find
3252         /// channel data Err(DecodeError::InvalidValue) will be returned.
3253         ///
3254         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
3255         /// this struct.
3256         pub channel_monitors: &'a HashMap<OutPoint, &'a ChannelMonitor>,
3257 }
3258
3259 impl<'a, R : ::std::io::Read> ReadableArgs<R, ChannelManagerReadArgs<'a>> for (Sha256dHash, ChannelManager) {
3260         fn read(reader: &mut R, args: ChannelManagerReadArgs<'a>) -> Result<Self, DecodeError> {
3261                 let _ver: u8 = Readable::read(reader)?;
3262                 let min_ver: u8 = Readable::read(reader)?;
3263                 if min_ver > SERIALIZATION_VERSION {
3264                         return Err(DecodeError::UnknownVersion);
3265                 }
3266
3267                 let genesis_hash: Sha256dHash = Readable::read(reader)?;
3268                 let latest_block_height: u32 = Readable::read(reader)?;
3269                 let last_block_hash: Sha256dHash = Readable::read(reader)?;
3270
3271                 let mut closed_channels = Vec::new();
3272
3273                 let channel_count: u64 = Readable::read(reader)?;
3274                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
3275                 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3276                 let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3277                 for _ in 0..channel_count {
3278                         let mut channel: Channel = ReadableArgs::read(reader, args.logger.clone())?;
3279                         if channel.last_block_connected != last_block_hash {
3280                                 return Err(DecodeError::InvalidValue);
3281                         }
3282
3283                         let funding_txo = channel.channel_monitor().get_funding_txo().ok_or(DecodeError::InvalidValue)?;
3284                         funding_txo_set.insert(funding_txo.clone());
3285                         if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
3286                                 if channel.get_cur_local_commitment_transaction_number() != monitor.get_cur_local_commitment_number() ||
3287                                                 channel.get_revoked_remote_commitment_transaction_number() != monitor.get_min_seen_secret() ||
3288                                                 channel.get_cur_remote_commitment_transaction_number() != monitor.get_cur_remote_commitment_number() {
3289                                         let mut force_close_res = channel.force_shutdown();
3290                                         force_close_res.0 = monitor.get_latest_local_commitment_txn();
3291                                         closed_channels.push(force_close_res);
3292                                 } else {
3293                                         if let Some(short_channel_id) = channel.get_short_channel_id() {
3294                                                 short_to_id.insert(short_channel_id, channel.channel_id());
3295                                         }
3296                                         by_id.insert(channel.channel_id(), channel);
3297                                 }
3298                         } else {
3299                                 return Err(DecodeError::InvalidValue);
3300                         }
3301                 }
3302
3303                 for (ref funding_txo, ref monitor) in args.channel_monitors.iter() {
3304                         if !funding_txo_set.contains(funding_txo) {
3305                                 closed_channels.push((monitor.get_latest_local_commitment_txn(), Vec::new()));
3306                         }
3307                 }
3308
3309                 let forward_htlcs_count: u64 = Readable::read(reader)?;
3310                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
3311                 for _ in 0..forward_htlcs_count {
3312                         let short_channel_id = Readable::read(reader)?;
3313                         let pending_forwards_count: u64 = Readable::read(reader)?;
3314                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, 128));
3315                         for _ in 0..pending_forwards_count {
3316                                 pending_forwards.push(Readable::read(reader)?);
3317                         }
3318                         forward_htlcs.insert(short_channel_id, pending_forwards);
3319                 }
3320
3321                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
3322                 let mut claimable_htlcs = HashMap::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
3323                 for _ in 0..claimable_htlcs_count {
3324                         let payment_hash = Readable::read(reader)?;
3325                         let previous_hops_len: u64 = Readable::read(reader)?;
3326                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, 2));
3327                         for _ in 0..previous_hops_len {
3328                                 previous_hops.push(Readable::read(reader)?);
3329                         }
3330                         claimable_htlcs.insert(payment_hash, previous_hops);
3331                 }
3332
3333                 let channel_manager = ChannelManager {
3334                         genesis_hash,
3335                         fee_estimator: args.fee_estimator,
3336                         monitor: args.monitor,
3337                         chain_monitor: args.chain_monitor,
3338                         tx_broadcaster: args.tx_broadcaster,
3339
3340                         latest_block_height: AtomicUsize::new(latest_block_height as usize),
3341                         last_block_hash: Mutex::new(last_block_hash),
3342                         secp_ctx: Secp256k1::new(),
3343
3344                         channel_state: Mutex::new(ChannelHolder {
3345                                 by_id,
3346                                 short_to_id,
3347                                 next_forward: Instant::now(),
3348                                 forward_htlcs,
3349                                 claimable_htlcs,
3350                                 pending_msg_events: Vec::new(),
3351                         }),
3352                         our_network_key: args.keys_manager.get_node_secret(),
3353
3354                         pending_events: Mutex::new(Vec::new()),
3355                         total_consistency_lock: RwLock::new(()),
3356                         keys_manager: args.keys_manager,
3357                         logger: args.logger,
3358                         default_configuration: args.default_config,
3359                 };
3360
3361                 for close_res in closed_channels.drain(..) {
3362                         channel_manager.finish_force_close_channel(close_res);
3363                         //TODO: Broadcast channel update for closed channels, but only after we've made a
3364                         //connection or two.
3365                 }
3366
3367                 Ok((last_block_hash.clone(), channel_manager))
3368         }
3369 }
3370
3371 #[cfg(test)]
3372 mod tests {
3373         use chain::chaininterface;
3374         use chain::transaction::OutPoint;
3375         use chain::chaininterface::{ChainListener, ChainWatchInterface};
3376         use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor};
3377         use chain::keysinterface;
3378         use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
3379         use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,OnionKeys,PaymentFailReason,RAACommitmentOrder, PaymentPreimage, PaymentHash};
3380         use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, ManyChannelMonitor};
3381         use ln::channel::{ACCEPTED_HTLC_SCRIPT_WEIGHT, OFFERED_HTLC_SCRIPT_WEIGHT};
3382         use ln::router::{Route, RouteHop, Router};
3383         use ln::msgs;
3384         use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler};
3385         use util::test_utils;
3386         use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
3387         use util::errors::APIError;
3388         use util::logger::Logger;
3389         use util::ser::{Writeable, Writer, ReadableArgs};
3390         use util::config::UserConfig;
3391
3392         use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
3393         use bitcoin::util::bip143;
3394         use bitcoin::util::address::Address;
3395         use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
3396         use bitcoin::blockdata::block::{Block, BlockHeader};
3397         use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType};
3398         use bitcoin::blockdata::script::{Builder, Script};
3399         use bitcoin::blockdata::opcodes;
3400         use bitcoin::blockdata::constants::genesis_block;
3401         use bitcoin::network::constants::Network;
3402
3403         use hex;
3404
3405         use secp256k1::{Secp256k1, Message};
3406         use secp256k1::key::{PublicKey,SecretKey};
3407
3408         use crypto::sha2::Sha256;
3409         use crypto::digest::Digest;
3410
3411         use rand::{thread_rng,Rng};
3412
3413         use std::cell::RefCell;
3414         use std::collections::{BTreeSet, HashMap, HashSet};
3415         use std::default::Default;
3416         use std::rc::Rc;
3417         use std::sync::{Arc, Mutex};
3418         use std::sync::atomic::Ordering;
3419         use std::time::Instant;
3420         use std::mem;
3421
3422         fn build_test_onion_keys() -> Vec<OnionKeys> {
3423                 // Keys from BOLT 4, used in both test vector tests
3424                 let secp_ctx = Secp256k1::new();
3425
3426                 let route = Route {
3427                         hops: vec!(
3428                                         RouteHop {
3429                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
3430                                                 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
3431                                         },
3432                                         RouteHop {
3433                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
3434                                                 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
3435                                         },
3436                                         RouteHop {
3437                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
3438                                                 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
3439                                         },
3440                                         RouteHop {
3441                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..]).unwrap(),
3442                                                 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
3443                                         },
3444                                         RouteHop {
3445                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145").unwrap()[..]).unwrap(),
3446                                                 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
3447                                         },
3448                         ),
3449                 };
3450
3451                 let session_priv = SecretKey::from_slice(&secp_ctx, &hex::decode("4141414141414141414141414141414141414141414141414141414141414141").unwrap()[..]).unwrap();
3452
3453                 let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
3454                 assert_eq!(onion_keys.len(), route.hops.len());
3455                 onion_keys
3456         }
3457
3458         #[test]
3459         fn onion_vectors() {
3460                 // Packet creation test vectors from BOLT 4
3461                 let onion_keys = build_test_onion_keys();
3462
3463                 assert_eq!(onion_keys[0].shared_secret[..], hex::decode("53eb63ea8a3fec3b3cd433b85cd62a4b145e1dda09391b348c4e1cd36a03ea66").unwrap()[..]);
3464                 assert_eq!(onion_keys[0].blinding_factor[..], hex::decode("2ec2e5da605776054187180343287683aa6a51b4b1c04d6dd49c45d8cffb3c36").unwrap()[..]);
3465                 assert_eq!(onion_keys[0].ephemeral_pubkey.serialize()[..], hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]);
3466                 assert_eq!(onion_keys[0].rho, hex::decode("ce496ec94def95aadd4bec15cdb41a740c9f2b62347c4917325fcc6fb0453986").unwrap()[..]);
3467                 assert_eq!(onion_keys[0].mu, hex::decode("b57061dc6d0a2b9f261ac410c8b26d64ac5506cbba30267a649c28c179400eba").unwrap()[..]);
3468
3469                 assert_eq!(onion_keys[1].shared_secret[..], hex::decode("a6519e98832a0b179f62123b3567c106db99ee37bef036e783263602f3488fae").unwrap()[..]);
3470                 assert_eq!(onion_keys[1].blinding_factor[..], hex::decode("bf66c28bc22e598cfd574a1931a2bafbca09163df2261e6d0056b2610dab938f").unwrap()[..]);
3471                 assert_eq!(onion_keys[1].ephemeral_pubkey.serialize()[..], hex::decode("028f9438bfbf7feac2e108d677e3a82da596be706cc1cf342b75c7b7e22bf4e6e2").unwrap()[..]);
3472                 assert_eq!(onion_keys[1].rho, hex::decode("450ffcabc6449094918ebe13d4f03e433d20a3d28a768203337bc40b6e4b2c59").unwrap()[..]);
3473                 assert_eq!(onion_keys[1].mu, hex::decode("05ed2b4a3fb023c2ff5dd6ed4b9b6ea7383f5cfe9d59c11d121ec2c81ca2eea9").unwrap()[..]);
3474
3475                 assert_eq!(onion_keys[2].shared_secret[..], hex::decode("3a6b412548762f0dbccce5c7ae7bb8147d1caf9b5471c34120b30bc9c04891cc").unwrap()[..]);
3476                 assert_eq!(onion_keys[2].blinding_factor[..], hex::decode("a1f2dadd184eb1627049673f18c6325814384facdee5bfd935d9cb031a1698a5").unwrap()[..]);
3477                 assert_eq!(onion_keys[2].ephemeral_pubkey.serialize()[..], hex::decode("03bfd8225241ea71cd0843db7709f4c222f62ff2d4516fd38b39914ab6b83e0da0").unwrap()[..]);
3478                 assert_eq!(onion_keys[2].rho, hex::decode("11bf5c4f960239cb37833936aa3d02cea82c0f39fd35f566109c41f9eac8deea").unwrap()[..]);
3479                 assert_eq!(onion_keys[2].mu, hex::decode("caafe2820fa00eb2eeb78695ae452eba38f5a53ed6d53518c5c6edf76f3f5b78").unwrap()[..]);
3480
3481                 assert_eq!(onion_keys[3].shared_secret[..], hex::decode("21e13c2d7cfe7e18836df50872466117a295783ab8aab0e7ecc8c725503ad02d").unwrap()[..]);
3482                 assert_eq!(onion_keys[3].blinding_factor[..], hex::decode("7cfe0b699f35525029ae0fa437c69d0f20f7ed4e3916133f9cacbb13c82ff262").unwrap()[..]);
3483                 assert_eq!(onion_keys[3].ephemeral_pubkey.serialize()[..], hex::decode("031dde6926381289671300239ea8e57ffaf9bebd05b9a5b95beaf07af05cd43595").unwrap()[..]);
3484                 assert_eq!(onion_keys[3].rho, hex::decode("cbe784ab745c13ff5cffc2fbe3e84424aa0fd669b8ead4ee562901a4a4e89e9e").unwrap()[..]);
3485                 assert_eq!(onion_keys[3].mu, hex::decode("5052aa1b3d9f0655a0932e50d42f0c9ba0705142c25d225515c45f47c0036ee9").unwrap()[..]);
3486
3487                 assert_eq!(onion_keys[4].shared_secret[..], hex::decode("b5756b9b542727dbafc6765a49488b023a725d631af688fc031217e90770c328").unwrap()[..]);
3488                 assert_eq!(onion_keys[4].blinding_factor[..], hex::decode("c96e00dddaf57e7edcd4fb5954be5b65b09f17cb6d20651b4e90315be5779205").unwrap()[..]);
3489                 assert_eq!(onion_keys[4].ephemeral_pubkey.serialize()[..], hex::decode("03a214ebd875aab6ddfd77f22c5e7311d7f77f17a169e599f157bbcdae8bf071f4").unwrap()[..]);
3490                 assert_eq!(onion_keys[4].rho, hex::decode("034e18b8cc718e8af6339106e706c52d8df89e2b1f7e9142d996acf88df8799b").unwrap()[..]);
3491                 assert_eq!(onion_keys[4].mu, hex::decode("8e45e5c61c2b24cb6382444db6698727afb063adecd72aada233d4bf273d975a").unwrap()[..]);
3492
3493                 // Test vectors below are flat-out wrong: they claim to set outgoing_cltv_value to non-0 :/
3494                 let payloads = vec!(
3495                         msgs::OnionHopData {
3496                                 realm: 0,
3497                                 data: msgs::OnionRealm0HopData {
3498                                         short_channel_id: 0,
3499                                         amt_to_forward: 0,
3500                                         outgoing_cltv_value: 0,
3501                                 },
3502                                 hmac: [0; 32],
3503                         },
3504                         msgs::OnionHopData {
3505                                 realm: 0,
3506                                 data: msgs::OnionRealm0HopData {
3507                                         short_channel_id: 0x0101010101010101,
3508                                         amt_to_forward: 0x0100000001,
3509                                         outgoing_cltv_value: 0,
3510                                 },
3511                                 hmac: [0; 32],
3512                         },
3513                         msgs::OnionHopData {
3514                                 realm: 0,
3515                                 data: msgs::OnionRealm0HopData {
3516                                         short_channel_id: 0x0202020202020202,
3517                                         amt_to_forward: 0x0200000002,
3518                                         outgoing_cltv_value: 0,
3519                                 },
3520                                 hmac: [0; 32],
3521                         },
3522                         msgs::OnionHopData {
3523                                 realm: 0,
3524                                 data: msgs::OnionRealm0HopData {
3525                                         short_channel_id: 0x0303030303030303,
3526                                         amt_to_forward: 0x0300000003,
3527                                         outgoing_cltv_value: 0,
3528                                 },
3529                                 hmac: [0; 32],
3530                         },
3531                         msgs::OnionHopData {
3532                                 realm: 0,
3533                                 data: msgs::OnionRealm0HopData {
3534                                         short_channel_id: 0x0404040404040404,
3535                                         amt_to_forward: 0x0400000004,
3536                                         outgoing_cltv_value: 0,
3537                                 },
3538                                 hmac: [0; 32],
3539                         },
3540                 );
3541
3542                 let packet = ChannelManager::construct_onion_packet(payloads, onion_keys, &PaymentHash([0x42; 32]));
3543                 // Just check the final packet encoding, as it includes all the per-hop vectors in it
3544                 // anyway...
3545                 assert_eq!(packet.encode(), hex::decode("0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619e5f14350c2a76fc232b5e46d421e9615471ab9e0bc887beff8c95fdb878f7b3a716a996c7845c93d90e4ecbb9bde4ece2f69425c99e4bc820e44485455f135edc0d10f7d61ab590531cf08000179a333a347f8b4072f216400406bdf3bf038659793d4a1fd7b246979e3150a0a4cb052c9ec69acf0f48c3d39cd55675fe717cb7d80ce721caad69320c3a469a202f1e468c67eaf7a7cd8226d0fd32f7b48084dca885d56047694762b67021713ca673929c163ec36e04e40ca8e1c6d17569419d3039d9a1ec866abe044a9ad635778b961fc0776dc832b3a451bd5d35072d2269cf9b040f6b7a7dad84fb114ed413b1426cb96ceaf83825665ed5a1d002c1687f92465b49ed4c7f0218ff8c6c7dd7221d589c65b3b9aaa71a41484b122846c7c7b57e02e679ea8469b70e14fe4f70fee4d87b910cf144be6fe48eef24da475c0b0bcc6565ae82cd3f4e3b24c76eaa5616c6111343306ab35c1fe5ca4a77c0e314ed7dba39d6f1e0de791719c241a939cc493bea2bae1c1e932679ea94d29084278513c77b899cc98059d06a27d171b0dbdf6bee13ddc4fc17a0c4d2827d488436b57baa167544138ca2e64a11b43ac8a06cd0c2fba2d4d900ed2d9205305e2d7383cc98dacb078133de5f6fb6bed2ef26ba92cea28aafc3b9948dd9ae5559e8bd6920b8cea462aa445ca6a95e0e7ba52961b181c79e73bd581821df2b10173727a810c92b83b5ba4a0403eb710d2ca10689a35bec6c3a708e9e92f7d78ff3c5d9989574b00c6736f84c199256e76e19e78f0c98a9d580b4a658c84fc8f2096c2fbea8f5f8c59d0fdacb3be2802ef802abbecb3aba4acaac69a0e965abd8981e9896b1f6ef9d60f7a164b371af869fd0e48073742825e9434fc54da837e120266d53302954843538ea7c6c3dbfb4ff3b2fdbe244437f2a153ccf7bdb4c92aa08102d4f3cff2ae5ef86fab4653595e6a5837fa2f3e29f27a9cde5966843fb847a4a61f1e76c281fe8bb2b0a181d096100db5a1a5ce7a910238251a43ca556712eaadea167fb4d7d75825e440f3ecd782036d7574df8bceacb397abefc5f5254d2722215c53ff54af8299aaaad642c6d72a14d27882d9bbd539e1cc7a527526ba89b8c037ad09120e98ab042d3e8652b31ae0e478516bfaf88efca9f3676ffe99d2819dcaeb7610a626695f53117665d267d3f7abebd6bbd6733f645c72c389f03855bdf1e4b8075b516569b118233a0f0971d24b83113c0b096f5216a207ca99a7cddc81c130923fe3d91e7508c9ac5f2e914ff5dccab9e558566fa14efb34ac98d878580814b94b73acbfde9072f30b881f7f0fff42d4045d1ace6322d86a97d164aa84d93a60498065cc7c20e636f5862dc81531a88c60305a2e59a985be327a6902e4bed986dbf4a0b50c217af0ea7fdf9ab37f9ea1a1aaa72f54cf40154ea9b269f1a7c09f9f43245109431a175d50e2db0132337baa0ef97eed0fcf20489da36b79a1172faccc2f7ded7c60e00694282d93359c4682135642bc81f433574aa8ef0c97b4ade7ca372c5ffc23c7eddd839bab4e0f14d6df15c9dbeab176bec8b5701cf054eb3072f6dadc98f88819042bf10c407516ee58bce33fbe3b3d86a54255e577db4598e30a135361528c101683a5fcde7e8ba53f3456254be8f45fe3a56120ae96ea3773631fcb3873aa3abd91bcff00bd38bd43697a2e789e00da6077482e7b1b1a677b5afae4c54e6cbdf7377b694eb7d7a5b913476a5be923322d3de06060fd5e819635232a2cf4f0731da13b8546d1d6d4f8d75b9fce6c2341a71b0ea6f780df54bfdb0dd5cd9855179f602f9172307c7268724c3618e6817abd793adc214a0dc0bc616816632f27ea336fb56dfd").unwrap());
3546         }
3547
3548         #[test]
3549         fn test_failure_packet_onion() {
3550                 // Returning Errors test vectors from BOLT 4
3551
3552                 let onion_keys = build_test_onion_keys();
3553                 let onion_error = ChannelManager::build_failure_packet(&onion_keys[4].shared_secret[..], 0x2002, &[0; 0]);
3554                 assert_eq!(onion_error.encode(), hex::decode("4c2fc8bc08510334b6833ad9c3e79cd1b52ae59dfe5c2a4b23ead50f09f7ee0b0002200200fe0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap());
3555
3556                 let onion_packet_1 = ChannelManager::encrypt_failure_packet(&onion_keys[4].shared_secret[..], &onion_error.encode()[..]);
3557                 assert_eq!(onion_packet_1.data, hex::decode("a5e6bd0c74cb347f10cce367f949098f2457d14c046fd8a22cb96efb30b0fdcda8cb9168b50f2fd45edd73c1b0c8b33002df376801ff58aaa94000bf8a86f92620f343baef38a580102395ae3abf9128d1047a0736ff9b83d456740ebbb4aeb3aa9737f18fb4afb4aa074fb26c4d702f42968888550a3bded8c05247e045b866baef0499f079fdaeef6538f31d44deafffdfd3afa2fb4ca9082b8f1c465371a9894dd8c243fb4847e004f5256b3e90e2edde4c9fb3082ddfe4d1e734cacd96ef0706bf63c9984e22dc98851bcccd1c3494351feb458c9c6af41c0044bea3c47552b1d992ae542b17a2d0bba1a096c78d169034ecb55b6e3a7263c26017f033031228833c1daefc0dedb8cf7c3e37c9c37ebfe42f3225c326e8bcfd338804c145b16e34e4").unwrap());
3558
3559                 let onion_packet_2 = ChannelManager::encrypt_failure_packet(&onion_keys[3].shared_secret[..], &onion_packet_1.data[..]);
3560                 assert_eq!(onion_packet_2.data, hex::decode("c49a1ce81680f78f5f2000cda36268de34a3f0a0662f55b4e837c83a8773c22aa081bab1616a0011585323930fa5b9fae0c85770a2279ff59ec427ad1bbff9001c0cd1497004bd2a0f68b50704cf6d6a4bf3c8b6a0833399a24b3456961ba00736785112594f65b6b2d44d9f5ea4e49b5e1ec2af978cbe31c67114440ac51a62081df0ed46d4a3df295da0b0fe25c0115019f03f15ec86fabb4c852f83449e812f141a9395b3f70b766ebbd4ec2fae2b6955bd8f32684c15abfe8fd3a6261e52650e8807a92158d9f1463261a925e4bfba44bd20b166d532f0017185c3a6ac7957adefe45559e3072c8dc35abeba835a8cb01a71a15c736911126f27d46a36168ca5ef7dccd4e2886212602b181463e0dd30185c96348f9743a02aca8ec27c0b90dca270").unwrap());
3561
3562                 let onion_packet_3 = ChannelManager::encrypt_failure_packet(&onion_keys[2].shared_secret[..], &onion_packet_2.data[..]);
3563                 assert_eq!(onion_packet_3.data, hex::decode("a5d3e8634cfe78b2307d87c6d90be6fe7855b4f2cc9b1dfb19e92e4b79103f61ff9ac25f412ddfb7466e74f81b3e545563cdd8f5524dae873de61d7bdfccd496af2584930d2b566b4f8d3881f8c043df92224f38cf094cfc09d92655989531524593ec6d6caec1863bdfaa79229b5020acc034cd6deeea1021c50586947b9b8e6faa83b81fbfa6133c0af5d6b07c017f7158fa94f0d206baf12dda6b68f785b773b360fd0497e16cc402d779c8d48d0fa6315536ef0660f3f4e1865f5b38ea49c7da4fd959de4e83ff3ab686f059a45c65ba2af4a6a79166aa0f496bf04d06987b6d2ea205bdb0d347718b9aeff5b61dfff344993a275b79717cd815b6ad4c0beb568c4ac9c36ff1c315ec1119a1993c4b61e6eaa0375e0aaf738ac691abd3263bf937e3").unwrap());
3564
3565                 let onion_packet_4 = ChannelManager::encrypt_failure_packet(&onion_keys[1].shared_secret[..], &onion_packet_3.data[..]);
3566                 assert_eq!(onion_packet_4.data, hex::decode("aac3200c4968f56b21f53e5e374e3a2383ad2b1b6501bbcc45abc31e59b26881b7dfadbb56ec8dae8857add94e6702fb4c3a4de22e2e669e1ed926b04447fc73034bb730f4932acd62727b75348a648a1128744657ca6a4e713b9b646c3ca66cac02cdab44dd3439890ef3aaf61708714f7375349b8da541b2548d452d84de7084bb95b3ac2345201d624d31f4d52078aa0fa05a88b4e20202bd2b86ac5b52919ea305a8949de95e935eed0319cf3cf19ebea61d76ba92532497fcdc9411d06bcd4275094d0a4a3c5d3a945e43305a5a9256e333e1f64dbca5fcd4e03a39b9012d197506e06f29339dfee3331995b21615337ae060233d39befea925cc262873e0530408e6990f1cbd233a150ef7b004ff6166c70c68d9f8c853c1abca640b8660db2921").unwrap());
3567
3568                 let onion_packet_5 = ChannelManager::encrypt_failure_packet(&onion_keys[0].shared_secret[..], &onion_packet_4.data[..]);
3569                 assert_eq!(onion_packet_5.data, hex::decode("9c5add3963fc7f6ed7f148623c84134b5647e1306419dbe2174e523fa9e2fbed3a06a19f899145610741c83ad40b7712aefaddec8c6baf7325d92ea4ca4d1df8bce517f7e54554608bf2bd8071a4f52a7a2f7ffbb1413edad81eeea5785aa9d990f2865dc23b4bc3c301a94eec4eabebca66be5cf638f693ec256aec514620cc28ee4a94bd9565bc4d4962b9d3641d4278fb319ed2b84de5b665f307a2db0f7fbb757366067d88c50f7e829138fde4f78d39b5b5802f1b92a8a820865af5cc79f9f30bc3f461c66af95d13e5e1f0381c184572a91dee1c849048a647a1158cf884064deddbf1b0b88dfe2f791428d0ba0f6fb2f04e14081f69165ae66d9297c118f0907705c9c4954a199bae0bb96fad763d690e7daa6cfda59ba7f2c8d11448b604d12d").unwrap());
3570         }
3571
3572         fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
3573                 assert!(chain.does_match_tx(tx));
3574                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3575                 chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
3576                 for i in 2..100 {
3577                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3578                         chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
3579                 }
3580         }
3581
3582         struct Node {
3583                 chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
3584                 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
3585                 chan_monitor: Arc<test_utils::TestChannelMonitor>,
3586                 node: Arc<ChannelManager>,
3587                 router: Router,
3588                 node_seed: [u8; 32],
3589                 network_payment_count: Rc<RefCell<u8>>,
3590                 network_chan_count: Rc<RefCell<u32>>,
3591         }
3592         impl Drop for Node {
3593                 fn drop(&mut self) {
3594                         if !::std::thread::panicking() {
3595                                 // Check that we processed all pending events
3596                                 assert_eq!(self.node.get_and_clear_pending_msg_events().len(), 0);
3597                                 assert_eq!(self.node.get_and_clear_pending_events().len(), 0);
3598                                 assert_eq!(self.chan_monitor.added_monitors.lock().unwrap().len(), 0);
3599                         }
3600                 }
3601         }
3602
3603         fn create_chan_between_nodes(node_a: &Node, node_b: &Node) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3604                 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001)
3605         }
3606
3607         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) {
3608                 let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat);
3609                 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
3610                 (announcement, as_update, bs_update, channel_id, tx)
3611         }
3612
3613         macro_rules! get_revoke_commit_msgs {
3614                 ($node: expr, $node_id: expr) => {
3615                         {
3616                                 let events = $node.node.get_and_clear_pending_msg_events();
3617                                 assert_eq!(events.len(), 2);
3618                                 (match events[0] {
3619                                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3620                                                 assert_eq!(*node_id, $node_id);
3621                                                 (*msg).clone()
3622                                         },
3623                                         _ => panic!("Unexpected event"),
3624                                 }, match events[1] {
3625                                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3626                                                 assert_eq!(*node_id, $node_id);
3627                                                 assert!(updates.update_add_htlcs.is_empty());
3628                                                 assert!(updates.update_fulfill_htlcs.is_empty());
3629                                                 assert!(updates.update_fail_htlcs.is_empty());
3630                                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
3631                                                 assert!(updates.update_fee.is_none());
3632                                                 updates.commitment_signed.clone()
3633                                         },
3634                                         _ => panic!("Unexpected event"),
3635                                 })
3636                         }
3637                 }
3638         }
3639
3640         macro_rules! get_event_msg {
3641                 ($node: expr, $event_type: path, $node_id: expr) => {
3642                         {
3643                                 let events = $node.node.get_and_clear_pending_msg_events();
3644                                 assert_eq!(events.len(), 1);
3645                                 match events[0] {
3646                                         $event_type { ref node_id, ref msg } => {
3647                                                 assert_eq!(*node_id, $node_id);
3648                                                 (*msg).clone()
3649                                         },
3650                                         _ => panic!("Unexpected event"),
3651                                 }
3652                         }
3653                 }
3654         }
3655
3656         macro_rules! get_htlc_update_msgs {
3657                 ($node: expr, $node_id: expr) => {
3658                         {
3659                                 let events = $node.node.get_and_clear_pending_msg_events();
3660                                 assert_eq!(events.len(), 1);
3661                                 match events[0] {
3662                                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3663                                                 assert_eq!(*node_id, $node_id);
3664                                                 (*updates).clone()
3665                                         },
3666                                         _ => panic!("Unexpected event"),
3667                                 }
3668                         }
3669                 }
3670         }
3671
3672         macro_rules! get_feerate {
3673                 ($node: expr, $channel_id: expr) => {
3674                         {
3675                                 let chan_lock = $node.node.channel_state.lock().unwrap();
3676                                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
3677                                 chan.get_feerate()
3678                         }
3679                 }
3680         }
3681
3682
3683         fn create_chan_between_nodes_with_value_init(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> Transaction {
3684                 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
3685                 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();
3686                 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();
3687
3688                 let chan_id = *node_a.network_chan_count.borrow();
3689                 let tx;
3690                 let funding_output;
3691
3692                 let events_2 = node_a.node.get_and_clear_pending_events();
3693                 assert_eq!(events_2.len(), 1);
3694                 match events_2[0] {
3695                         Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
3696                                 assert_eq!(*channel_value_satoshis, channel_value);
3697                                 assert_eq!(user_channel_id, 42);
3698
3699                                 tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
3700                                         value: *channel_value_satoshis, script_pubkey: output_script.clone(),
3701                                 }]};
3702                                 funding_output = OutPoint::new(tx.txid(), 0);
3703
3704                                 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
3705                                 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3706                                 assert_eq!(added_monitors.len(), 1);
3707                                 assert_eq!(added_monitors[0].0, funding_output);
3708                                 added_monitors.clear();
3709                         },
3710                         _ => panic!("Unexpected event"),
3711                 }
3712
3713                 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();
3714                 {
3715                         let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
3716                         assert_eq!(added_monitors.len(), 1);
3717                         assert_eq!(added_monitors[0].0, funding_output);
3718                         added_monitors.clear();
3719                 }
3720
3721                 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();
3722                 {
3723                         let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3724                         assert_eq!(added_monitors.len(), 1);
3725                         assert_eq!(added_monitors[0].0, funding_output);
3726                         added_monitors.clear();
3727                 }
3728
3729                 let events_4 = node_a.node.get_and_clear_pending_events();
3730                 assert_eq!(events_4.len(), 1);
3731                 match events_4[0] {
3732                         Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
3733                                 assert_eq!(user_channel_id, 42);
3734                                 assert_eq!(*funding_txo, funding_output);
3735                         },
3736                         _ => panic!("Unexpected event"),
3737                 };
3738
3739                 tx
3740         }
3741
3742         fn create_chan_between_nodes_with_value_confirm(node_a: &Node, node_b: &Node, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
3743                 confirm_transaction(&node_b.chain_monitor, &tx, tx.version);
3744                 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();
3745
3746                 let channel_id;
3747
3748                 confirm_transaction(&node_a.chain_monitor, &tx, tx.version);
3749                 let events_6 = node_a.node.get_and_clear_pending_msg_events();
3750                 assert_eq!(events_6.len(), 2);
3751                 ((match events_6[0] {
3752                         MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3753                                 channel_id = msg.channel_id.clone();
3754                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
3755                                 msg.clone()
3756                         },
3757                         _ => panic!("Unexpected event"),
3758                 }, match events_6[1] {
3759                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3760                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
3761                                 msg.clone()
3762                         },
3763                         _ => panic!("Unexpected event"),
3764                 }), channel_id)
3765         }
3766
3767         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) {
3768                 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat);
3769                 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
3770                 (msgs, chan_id, tx)
3771         }
3772
3773         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) {
3774                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0).unwrap();
3775                 let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
3776                 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1).unwrap();
3777
3778                 let events_7 = node_b.node.get_and_clear_pending_msg_events();
3779                 assert_eq!(events_7.len(), 1);
3780                 let (announcement, bs_update) = match events_7[0] {
3781                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3782                                 (msg, update_msg)
3783                         },
3784                         _ => panic!("Unexpected event"),
3785                 };
3786
3787                 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs).unwrap();
3788                 let events_8 = node_a.node.get_and_clear_pending_msg_events();
3789                 assert_eq!(events_8.len(), 1);
3790                 let as_update = match events_8[0] {
3791                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3792                                 assert!(*announcement == *msg);
3793                                 update_msg
3794                         },
3795                         _ => panic!("Unexpected event"),
3796                 };
3797
3798                 *node_a.network_chan_count.borrow_mut() += 1;
3799
3800                 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
3801         }
3802
3803         fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3804                 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001)
3805         }
3806
3807         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) {
3808                 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat);
3809                 for node in nodes {
3810                         assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
3811                         node.router.handle_channel_update(&chan_announcement.1).unwrap();
3812                         node.router.handle_channel_update(&chan_announcement.2).unwrap();
3813                 }
3814                 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
3815         }
3816
3817         macro_rules! check_spends {
3818                 ($tx: expr, $spends_tx: expr) => {
3819                         {
3820                                 let mut funding_tx_map = HashMap::new();
3821                                 let spends_tx = $spends_tx;
3822                                 funding_tx_map.insert(spends_tx.txid(), spends_tx);
3823                                 $tx.verify(&funding_tx_map).unwrap();
3824                         }
3825                 }
3826         }
3827
3828         macro_rules! get_closing_signed_broadcast {
3829                 ($node: expr, $dest_pubkey: expr) => {
3830                         {
3831                                 let events = $node.get_and_clear_pending_msg_events();
3832                                 assert!(events.len() == 1 || events.len() == 2);
3833                                 (match events[events.len() - 1] {
3834                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
3835                                                 assert_eq!(msg.contents.flags & 2, 2);
3836                                                 msg.clone()
3837                                         },
3838                                         _ => panic!("Unexpected event"),
3839                                 }, if events.len() == 2 {
3840                                         match events[0] {
3841                                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3842                                                         assert_eq!(*node_id, $dest_pubkey);
3843                                                         Some(msg.clone())
3844                                                 },
3845                                                 _ => panic!("Unexpected event"),
3846                                         }
3847                                 } else { None })
3848                         }
3849                 }
3850         }
3851
3852         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) {
3853                 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) };
3854                 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
3855                 let (tx_a, tx_b);
3856
3857                 node_a.close_channel(channel_id).unwrap();
3858                 node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id())).unwrap();
3859
3860                 let events_1 = node_b.get_and_clear_pending_msg_events();
3861                 assert!(events_1.len() >= 1);
3862                 let shutdown_b = match events_1[0] {
3863                         MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
3864                                 assert_eq!(node_id, &node_a.get_our_node_id());
3865                                 msg.clone()
3866                         },
3867                         _ => panic!("Unexpected event"),
3868                 };
3869
3870                 let closing_signed_b = if !close_inbound_first {
3871                         assert_eq!(events_1.len(), 1);
3872                         None
3873                 } else {
3874                         Some(match events_1[1] {
3875                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3876                                         assert_eq!(node_id, &node_a.get_our_node_id());
3877                                         msg.clone()
3878                                 },
3879                                 _ => panic!("Unexpected event"),
3880                         })
3881                 };
3882
3883                 node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b).unwrap();
3884                 let (as_update, bs_update) = if close_inbound_first {
3885                         assert!(node_a.get_and_clear_pending_msg_events().is_empty());
3886                         node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3887                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3888                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3889                         let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3890
3891                         node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
3892                         let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3893                         assert!(none_b.is_none());
3894                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3895                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3896                         (as_update, bs_update)
3897                 } else {
3898                         let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
3899
3900                         node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a).unwrap();
3901                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3902                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3903                         let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3904
3905                         node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3906                         let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3907                         assert!(none_a.is_none());
3908                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3909                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3910                         (as_update, bs_update)
3911                 };
3912                 assert_eq!(tx_a, tx_b);
3913                 check_spends!(tx_a, funding_tx);
3914
3915                 (as_update, bs_update, tx_a)
3916         }
3917
3918         struct SendEvent {
3919                 node_id: PublicKey,
3920                 msgs: Vec<msgs::UpdateAddHTLC>,
3921                 commitment_msg: msgs::CommitmentSigned,
3922         }
3923         impl SendEvent {
3924                 fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
3925                         assert!(updates.update_fulfill_htlcs.is_empty());
3926                         assert!(updates.update_fail_htlcs.is_empty());
3927                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3928                         assert!(updates.update_fee.is_none());
3929                         SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
3930                 }
3931
3932                 fn from_event(event: MessageSendEvent) -> SendEvent {
3933                         match event {
3934                                 MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
3935                                 _ => panic!("Unexpected event type!"),
3936                         }
3937                 }
3938
3939                 fn from_node(node: &Node) -> SendEvent {
3940                         let mut events = node.node.get_and_clear_pending_msg_events();
3941                         assert_eq!(events.len(), 1);
3942                         SendEvent::from_event(events.pop().unwrap())
3943                 }
3944         }
3945
3946         macro_rules! check_added_monitors {
3947                 ($node: expr, $count: expr) => {
3948                         {
3949                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
3950                                 assert_eq!(added_monitors.len(), $count);
3951                                 added_monitors.clear();
3952                         }
3953                 }
3954         }
3955
3956         macro_rules! commitment_signed_dance {
3957                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
3958                         {
3959                                 check_added_monitors!($node_a, 0);
3960                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3961                                 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3962                                 check_added_monitors!($node_a, 1);
3963                                 commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
3964                         }
3965                 };
3966                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
3967                         {
3968                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
3969                                 check_added_monitors!($node_b, 0);
3970                                 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3971                                 $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
3972                                 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3973                                 check_added_monitors!($node_b, 1);
3974                                 $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed).unwrap();
3975                                 let (bs_revoke_and_ack, extra_msg_option) = {
3976                                         let events = $node_b.node.get_and_clear_pending_msg_events();
3977                                         assert!(events.len() <= 2);
3978                                         (match events[0] {
3979                                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3980                                                         assert_eq!(*node_id, $node_a.node.get_our_node_id());
3981                                                         (*msg).clone()
3982                                                 },
3983                                                 _ => panic!("Unexpected event"),
3984                                         }, events.get(1).map(|e| e.clone()))
3985                                 };
3986                                 check_added_monitors!($node_b, 1);
3987                                 if $fail_backwards {
3988                                         assert!($node_a.node.get_and_clear_pending_events().is_empty());
3989                                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3990                                 }
3991                                 (extra_msg_option, bs_revoke_and_ack)
3992                         }
3993                 };
3994                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
3995                         {
3996                                 check_added_monitors!($node_a, 0);
3997                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3998                                 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3999                                 check_added_monitors!($node_a, 1);
4000                                 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
4001                                 assert!(extra_msg_option.is_none());
4002                                 bs_revoke_and_ack
4003                         }
4004                 };
4005                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
4006                         {
4007                                 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
4008                                 $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
4009                                 {
4010                                         let mut added_monitors = $node_a.chan_monitor.added_monitors.lock().unwrap();
4011                                         if $fail_backwards {
4012                                                 assert_eq!(added_monitors.len(), 2);
4013                                                 assert!(added_monitors[0].0 != added_monitors[1].0);
4014                                         } else {
4015                                                 assert_eq!(added_monitors.len(), 1);
4016                                         }
4017                                         added_monitors.clear();
4018                                 }
4019                                 extra_msg_option
4020                         }
4021                 };
4022                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
4023                         {
4024                                 assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
4025                         }
4026                 };
4027                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
4028                         {
4029                                 commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
4030                                 if $fail_backwards {
4031                                         let channel_state = $node_a.node.channel_state.lock().unwrap();
4032                                         assert_eq!(channel_state.pending_msg_events.len(), 1);
4033                                         if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
4034                                                 assert_ne!(*node_id, $node_b.node.get_our_node_id());
4035                                         } else { panic!("Unexpected event"); }
4036                                 } else {
4037                                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
4038                                 }
4039                         }
4040                 }
4041         }
4042
4043         macro_rules! get_payment_preimage_hash {
4044                 ($node: expr) => {
4045                         {
4046                                 let payment_preimage = PaymentPreimage([*$node.network_payment_count.borrow(); 32]);
4047                                 *$node.network_payment_count.borrow_mut() += 1;
4048                                 let mut payment_hash = PaymentHash([0; 32]);
4049                                 let mut sha = Sha256::new();
4050                                 sha.input(&payment_preimage.0[..]);
4051                                 sha.result(&mut payment_hash.0[..]);
4052                                 (payment_preimage, payment_hash)
4053                         }
4054                 }
4055         }
4056
4057         fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
4058                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4059
4060                 let mut payment_event = {
4061                         origin_node.node.send_payment(route, our_payment_hash).unwrap();
4062                         check_added_monitors!(origin_node, 1);
4063
4064                         let mut events = origin_node.node.get_and_clear_pending_msg_events();
4065                         assert_eq!(events.len(), 1);
4066                         SendEvent::from_event(events.remove(0))
4067                 };
4068                 let mut prev_node = origin_node;
4069
4070                 for (idx, &node) in expected_route.iter().enumerate() {
4071                         assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
4072
4073                         node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4074                         check_added_monitors!(node, 0);
4075                         commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
4076
4077                         let events_1 = node.node.get_and_clear_pending_events();
4078                         assert_eq!(events_1.len(), 1);
4079                         match events_1[0] {
4080                                 Event::PendingHTLCsForwardable { .. } => { },
4081                                 _ => panic!("Unexpected event"),
4082                         };
4083
4084                         node.node.channel_state.lock().unwrap().next_forward = Instant::now();
4085                         node.node.process_pending_htlc_forwards();
4086
4087                         if idx == expected_route.len() - 1 {
4088                                 let events_2 = node.node.get_and_clear_pending_events();
4089                                 assert_eq!(events_2.len(), 1);
4090                                 match events_2[0] {
4091                                         Event::PaymentReceived { ref payment_hash, amt } => {
4092                                                 assert_eq!(our_payment_hash, *payment_hash);
4093                                                 assert_eq!(amt, recv_value);
4094                                         },
4095                                         _ => panic!("Unexpected event"),
4096                                 }
4097                         } else {
4098                                 let mut events_2 = node.node.get_and_clear_pending_msg_events();
4099                                 assert_eq!(events_2.len(), 1);
4100                                 check_added_monitors!(node, 1);
4101                                 payment_event = SendEvent::from_event(events_2.remove(0));
4102                                 assert_eq!(payment_event.msgs.len(), 1);
4103                         }
4104
4105                         prev_node = node;
4106                 }
4107
4108                 (our_payment_preimage, our_payment_hash)
4109         }
4110
4111         fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: PaymentPreimage) {
4112                 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
4113                 check_added_monitors!(expected_route.last().unwrap(), 1);
4114
4115                 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
4116                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4117                 macro_rules! get_next_msgs {
4118                         ($node: expr) => {
4119                                 {
4120                                         let events = $node.node.get_and_clear_pending_msg_events();
4121                                         assert_eq!(events.len(), 1);
4122                                         match events[0] {
4123                                                 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 } } => {
4124                                                         assert!(update_add_htlcs.is_empty());
4125                                                         assert_eq!(update_fulfill_htlcs.len(), 1);
4126                                                         assert!(update_fail_htlcs.is_empty());
4127                                                         assert!(update_fail_malformed_htlcs.is_empty());
4128                                                         assert!(update_fee.is_none());
4129                                                         expected_next_node = node_id.clone();
4130                                                         Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()))
4131                                                 },
4132                                                 _ => panic!("Unexpected event"),
4133                                         }
4134                                 }
4135                         }
4136                 }
4137
4138                 macro_rules! last_update_fulfill_dance {
4139                         ($node: expr, $prev_node: 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, 0);
4143                                         assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4144                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4145                                 }
4146                         }
4147                 }
4148                 macro_rules! mid_update_fulfill_dance {
4149                         ($node: expr, $prev_node: expr, $new_msgs: expr) => {
4150                                 {
4151                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4152                                         check_added_monitors!($node, 1);
4153                                         let new_next_msgs = if $new_msgs {
4154                                                 get_next_msgs!($node)
4155                                         } else {
4156                                                 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4157                                                 None
4158                                         };
4159                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4160                                         next_msgs = new_next_msgs;
4161                                 }
4162                         }
4163                 }
4164
4165                 let mut prev_node = expected_route.last().unwrap();
4166                 for (idx, node) in expected_route.iter().rev().enumerate() {
4167                         assert_eq!(expected_next_node, node.node.get_our_node_id());
4168                         let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
4169                         if next_msgs.is_some() {
4170                                 mid_update_fulfill_dance!(node, prev_node, update_next_msgs);
4171                         } else if update_next_msgs {
4172                                 next_msgs = get_next_msgs!(node);
4173                         } else {
4174                                 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
4175                         }
4176                         if !skip_last && idx == expected_route.len() - 1 {
4177                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4178                         }
4179
4180                         prev_node = node;
4181                 }
4182
4183                 if !skip_last {
4184                         last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
4185                         let events = origin_node.node.get_and_clear_pending_events();
4186                         assert_eq!(events.len(), 1);
4187                         match events[0] {
4188                                 Event::PaymentSent { payment_preimage } => {
4189                                         assert_eq!(payment_preimage, our_payment_preimage);
4190                                 },
4191                                 _ => panic!("Unexpected event"),
4192                         }
4193                 }
4194         }
4195
4196         fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: PaymentPreimage) {
4197                 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage);
4198         }
4199
4200         const TEST_FINAL_CLTV: u32 = 32;
4201
4202         fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
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                 send_along_route(origin_node, route, expected_route, recv_value)
4210         }
4211
4212         fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
4213                 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();
4214                 assert_eq!(route.hops.len(), expected_route.len());
4215                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4216                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
4217                 }
4218
4219                 let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4220
4221                 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
4222                 match err {
4223                         APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
4224                         _ => panic!("Unknown error variants"),
4225                 };
4226         }
4227
4228         fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
4229                 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
4230                 claim_payment(&origin, expected_route, our_payment_preimage);
4231         }
4232
4233         fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: PaymentHash) {
4234                 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash, PaymentFailReason::PreimageUnknown));
4235                 check_added_monitors!(expected_route.last().unwrap(), 1);
4236
4237                 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
4238                 macro_rules! update_fail_dance {
4239                         ($node: expr, $prev_node: expr, $last_node: expr) => {
4240                                 {
4241                                         $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4242                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
4243                                 }
4244                         }
4245                 }
4246
4247                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4248                 let mut prev_node = expected_route.last().unwrap();
4249                 for (idx, node) in expected_route.iter().rev().enumerate() {
4250                         assert_eq!(expected_next_node, node.node.get_our_node_id());
4251                         if next_msgs.is_some() {
4252                                 // We may be the "last node" for the purpose of the commitment dance if we're
4253                                 // skipping the last node (implying it is disconnected) and we're the
4254                                 // second-to-last node!
4255                                 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
4256                         }
4257
4258                         let events = node.node.get_and_clear_pending_msg_events();
4259                         if !skip_last || idx != expected_route.len() - 1 {
4260                                 assert_eq!(events.len(), 1);
4261                                 match events[0] {
4262                                         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 } } => {
4263                                                 assert!(update_add_htlcs.is_empty());
4264                                                 assert!(update_fulfill_htlcs.is_empty());
4265                                                 assert_eq!(update_fail_htlcs.len(), 1);
4266                                                 assert!(update_fail_malformed_htlcs.is_empty());
4267                                                 assert!(update_fee.is_none());
4268                                                 expected_next_node = node_id.clone();
4269                                                 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
4270                                         },
4271                                         _ => panic!("Unexpected event"),
4272                                 }
4273                         } else {
4274                                 assert!(events.is_empty());
4275                         }
4276                         if !skip_last && idx == expected_route.len() - 1 {
4277                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4278                         }
4279
4280                         prev_node = node;
4281                 }
4282
4283                 if !skip_last {
4284                         update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
4285
4286                         let events = origin_node.node.get_and_clear_pending_events();
4287                         assert_eq!(events.len(), 1);
4288                         match events[0] {
4289                                 Event::PaymentFailed { payment_hash, rejected_by_dest } => {
4290                                         assert_eq!(payment_hash, our_payment_hash);
4291                                         assert!(rejected_by_dest);
4292                                 },
4293                                 _ => panic!("Unexpected event"),
4294                         }
4295                 }
4296         }
4297
4298         fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: PaymentHash) {
4299                 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
4300         }
4301
4302         fn create_network(node_count: usize) -> Vec<Node> {
4303                 let mut nodes = Vec::new();
4304                 let mut rng = thread_rng();
4305                 let secp_ctx = Secp256k1::new();
4306                 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
4307
4308                 let chan_count = Rc::new(RefCell::new(0));
4309                 let payment_count = Rc::new(RefCell::new(0));
4310
4311                 for _ in 0..node_count {
4312                         let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
4313                         let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
4314                         let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
4315                         let mut seed = [0; 32];
4316                         rng.fill_bytes(&mut seed);
4317                         let keys_manager = Arc::new(keysinterface::KeysManager::new(&seed, Network::Testnet, Arc::clone(&logger)));
4318                         let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone()));
4319                         let mut config = UserConfig::new();
4320                         config.channel_options.announced_channel = true;
4321                         config.channel_limits.force_announced_channel_preference = false;
4322                         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();
4323                         let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), chain_monitor.clone(), Arc::clone(&logger));
4324                         nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router, node_seed: seed,
4325                                 network_payment_count: payment_count.clone(),
4326                                 network_chan_count: chan_count.clone(),
4327                         });
4328                 }
4329
4330                 nodes
4331         }
4332
4333         #[test]
4334         fn test_async_inbound_update_fee() {
4335                 let mut nodes = create_network(2);
4336                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4337                 let channel_id = chan.2;
4338
4339                 // balancing
4340                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4341
4342                 // A                                        B
4343                 // update_fee                            ->
4344                 // send (1) commitment_signed            -.
4345                 //                                       <- update_add_htlc/commitment_signed
4346                 // send (2) RAA (awaiting remote revoke) -.
4347                 // (1) commitment_signed is delivered    ->
4348                 //                                       .- send (3) RAA (awaiting remote revoke)
4349                 // (2) RAA is delivered                  ->
4350                 //                                       .- send (4) commitment_signed
4351                 //                                       <- (3) RAA is delivered
4352                 // send (5) commitment_signed            -.
4353                 //                                       <- (4) commitment_signed is delivered
4354                 // send (6) RAA                          -.
4355                 // (5) commitment_signed is delivered    ->
4356                 //                                       <- RAA
4357                 // (6) RAA is delivered                  ->
4358
4359                 // First nodes[0] generates an update_fee
4360                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4361                 check_added_monitors!(nodes[0], 1);
4362
4363                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4364                 assert_eq!(events_0.len(), 1);
4365                 let (update_msg, commitment_signed) = match events_0[0] { // (1)
4366                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4367                                 (update_fee.as_ref(), commitment_signed)
4368                         },
4369                         _ => panic!("Unexpected event"),
4370                 };
4371
4372                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4373
4374                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4375                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4376                 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();
4377                 check_added_monitors!(nodes[1], 1);
4378
4379                 let payment_event = {
4380                         let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4381                         assert_eq!(events_1.len(), 1);
4382                         SendEvent::from_event(events_1.remove(0))
4383                 };
4384                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4385                 assert_eq!(payment_event.msgs.len(), 1);
4386
4387                 // ...now when the messages get delivered everyone should be happy
4388                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4389                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4390                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4391                 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4392                 check_added_monitors!(nodes[0], 1);
4393
4394                 // deliver(1), generate (3):
4395                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4396                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4397                 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
4398                 check_added_monitors!(nodes[1], 1);
4399
4400                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap(); // deliver (2)
4401                 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4402                 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
4403                 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
4404                 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
4405                 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
4406                 assert!(bs_update.update_fee.is_none()); // (4)
4407                 check_added_monitors!(nodes[1], 1);
4408
4409                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap(); // deliver (3)
4410                 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4411                 assert!(as_update.update_add_htlcs.is_empty()); // (5)
4412                 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
4413                 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
4414                 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
4415                 assert!(as_update.update_fee.is_none()); // (5)
4416                 check_added_monitors!(nodes[0], 1);
4417
4418                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed).unwrap(); // deliver (4)
4419                 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4420                 // only (6) so get_event_msg's assert(len == 1) passes
4421                 check_added_monitors!(nodes[0], 1);
4422
4423                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed).unwrap(); // deliver (5)
4424                 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4425                 check_added_monitors!(nodes[1], 1);
4426
4427                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4428                 check_added_monitors!(nodes[0], 1);
4429
4430                 let events_2 = nodes[0].node.get_and_clear_pending_events();
4431                 assert_eq!(events_2.len(), 1);
4432                 match events_2[0] {
4433                         Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
4434                         _ => panic!("Unexpected event"),
4435                 }
4436
4437                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap(); // deliver (6)
4438                 check_added_monitors!(nodes[1], 1);
4439         }
4440
4441         #[test]
4442         fn test_update_fee_unordered_raa() {
4443                 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
4444                 // crash in an earlier version of the update_fee patch)
4445                 let mut nodes = create_network(2);
4446                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4447                 let channel_id = chan.2;
4448
4449                 // balancing
4450                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4451
4452                 // First nodes[0] generates an update_fee
4453                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4454                 check_added_monitors!(nodes[0], 1);
4455
4456                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4457                 assert_eq!(events_0.len(), 1);
4458                 let update_msg = match events_0[0] { // (1)
4459                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
4460                                 update_fee.as_ref()
4461                         },
4462                         _ => panic!("Unexpected event"),
4463                 };
4464
4465                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4466
4467                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4468                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4469                 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();
4470                 check_added_monitors!(nodes[1], 1);
4471
4472                 let payment_event = {
4473                         let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4474                         assert_eq!(events_1.len(), 1);
4475                         SendEvent::from_event(events_1.remove(0))
4476                 };
4477                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4478                 assert_eq!(payment_event.msgs.len(), 1);
4479
4480                 // ...now when the messages get delivered everyone should be happy
4481                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4482                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4483                 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4484                 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4485                 check_added_monitors!(nodes[0], 1);
4486
4487                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap(); // deliver (2)
4488                 check_added_monitors!(nodes[1], 1);
4489
4490                 // We can't continue, sadly, because our (1) now has a bogus signature
4491         }
4492
4493         #[test]
4494         fn test_multi_flight_update_fee() {
4495                 let nodes = create_network(2);
4496                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4497                 let channel_id = chan.2;
4498
4499                 // A                                        B
4500                 // update_fee/commitment_signed          ->
4501                 //                                       .- send (1) RAA and (2) commitment_signed
4502                 // update_fee (never committed)          ->
4503                 // (3) update_fee                        ->
4504                 // We have to manually generate the above update_fee, it is allowed by the protocol but we
4505                 // don't track which updates correspond to which revoke_and_ack responses so we're in
4506                 // AwaitingRAA mode and will not generate the update_fee yet.
4507                 //                                       <- (1) RAA delivered
4508                 // (3) is generated and send (4) CS      -.
4509                 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
4510                 // know the per_commitment_point to use for it.
4511                 //                                       <- (2) commitment_signed delivered
4512                 // revoke_and_ack                        ->
4513                 //                                          B should send no response here
4514                 // (4) commitment_signed delivered       ->
4515                 //                                       <- RAA/commitment_signed delivered
4516                 // revoke_and_ack                        ->
4517
4518                 // First nodes[0] generates an update_fee
4519                 let initial_feerate = get_feerate!(nodes[0], channel_id);
4520                 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
4521                 check_added_monitors!(nodes[0], 1);
4522
4523                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4524                 assert_eq!(events_0.len(), 1);
4525                 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
4526                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4527                                 (update_fee.as_ref().unwrap(), commitment_signed)
4528                         },
4529                         _ => panic!("Unexpected event"),
4530                 };
4531
4532                 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
4533                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1).unwrap();
4534                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1).unwrap();
4535                 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4536                 check_added_monitors!(nodes[1], 1);
4537
4538                 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
4539                 // transaction:
4540                 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
4541                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4542                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4543
4544                 // Create the (3) update_fee message that nodes[0] will generate before it does...
4545                 let mut update_msg_2 = msgs::UpdateFee {
4546                         channel_id: update_msg_1.channel_id.clone(),
4547                         feerate_per_kw: (initial_feerate + 30) as u32,
4548                 };
4549
4550                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4551
4552                 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
4553                 // Deliver (3)
4554                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4555
4556                 // Deliver (1), generating (3) and (4)
4557                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap();
4558                 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4559                 check_added_monitors!(nodes[0], 1);
4560                 assert!(as_second_update.update_add_htlcs.is_empty());
4561                 assert!(as_second_update.update_fulfill_htlcs.is_empty());
4562                 assert!(as_second_update.update_fail_htlcs.is_empty());
4563                 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
4564                 // Check that the update_fee newly generated matches what we delivered:
4565                 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
4566                 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
4567
4568                 // Deliver (2) commitment_signed
4569                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
4570                 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4571                 check_added_monitors!(nodes[0], 1);
4572                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4573
4574                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap();
4575                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4576                 check_added_monitors!(nodes[1], 1);
4577
4578                 // Delever (4)
4579                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed).unwrap();
4580                 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4581                 check_added_monitors!(nodes[1], 1);
4582
4583                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4584                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4585                 check_added_monitors!(nodes[0], 1);
4586
4587                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment).unwrap();
4588                 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4589                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4590                 check_added_monitors!(nodes[0], 1);
4591
4592                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap();
4593                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4594                 check_added_monitors!(nodes[1], 1);
4595         }
4596
4597         #[test]
4598         fn test_update_fee_vanilla() {
4599                 let nodes = create_network(2);
4600                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4601                 let channel_id = chan.2;
4602
4603                 let feerate = get_feerate!(nodes[0], channel_id);
4604                 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
4605                 check_added_monitors!(nodes[0], 1);
4606
4607                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4608                 assert_eq!(events_0.len(), 1);
4609                 let (update_msg, commitment_signed) = match events_0[0] {
4610                                 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 } } => {
4611                                 (update_fee.as_ref(), commitment_signed)
4612                         },
4613                         _ => panic!("Unexpected event"),
4614                 };
4615                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4616
4617                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4618                 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4619                 check_added_monitors!(nodes[1], 1);
4620
4621                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4622                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4623                 check_added_monitors!(nodes[0], 1);
4624
4625                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4626                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4627                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4628                 check_added_monitors!(nodes[0], 1);
4629
4630                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4631                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4632                 check_added_monitors!(nodes[1], 1);
4633         }
4634
4635         #[test]
4636         fn test_update_fee_that_funder_cannot_afford() {
4637                 let nodes = create_network(2);
4638                 let channel_value = 1888;
4639                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000);
4640                 let channel_id = chan.2;
4641
4642                 let feerate = 260;
4643                 nodes[0].node.update_fee(channel_id, feerate).unwrap();
4644                 check_added_monitors!(nodes[0], 1);
4645                 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4646
4647                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap()).unwrap();
4648
4649                 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
4650
4651                 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
4652                 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
4653                 {
4654                         let chan_lock = nodes[1].node.channel_state.lock().unwrap();
4655                         let chan = chan_lock.by_id.get(&channel_id).unwrap();
4656
4657                         //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
4658                         let num_htlcs = chan.last_local_commitment_txn[0].output.len() - 2;
4659                         let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
4660                         let mut actual_fee = chan.last_local_commitment_txn[0].output.iter().fold(0, |acc, output| acc + output.value);
4661                         actual_fee = channel_value - actual_fee;
4662                         assert_eq!(total_fee, actual_fee);
4663                 } //drop the mutex
4664
4665                 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
4666                 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
4667                 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
4668                 check_added_monitors!(nodes[0], 1);
4669
4670                 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4671
4672                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap()).unwrap();
4673
4674                 //While producing the commitment_signed response after handling a received update_fee request the
4675                 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
4676                 //Should produce and error.
4677                 let err = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed).unwrap_err();
4678
4679                 assert!(match err.err {
4680                         "Funding remote cannot afford proposed new fee" => true,
4681                         _ => false,
4682                 });
4683
4684                 //clear the message we could not handle
4685                 nodes[1].node.get_and_clear_pending_msg_events();
4686         }
4687
4688         #[test]
4689         fn test_update_fee_with_fundee_update_add_htlc() {
4690                 let mut nodes = create_network(2);
4691                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4692                 let channel_id = chan.2;
4693
4694                 // balancing
4695                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4696
4697                 let feerate = get_feerate!(nodes[0], channel_id);
4698                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4699                 check_added_monitors!(nodes[0], 1);
4700
4701                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4702                 assert_eq!(events_0.len(), 1);
4703                 let (update_msg, commitment_signed) = match events_0[0] {
4704                                 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 } } => {
4705                                 (update_fee.as_ref(), commitment_signed)
4706                         },
4707                         _ => panic!("Unexpected event"),
4708                 };
4709                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4710                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4711                 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4712                 check_added_monitors!(nodes[1], 1);
4713
4714                 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
4715
4716                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
4717
4718                 // nothing happens since node[1] is in AwaitingRemoteRevoke
4719                 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
4720                 {
4721                         let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
4722                         assert_eq!(added_monitors.len(), 0);
4723                         added_monitors.clear();
4724                 }
4725                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4726                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4727                 // node[1] has nothing to do
4728
4729                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4730                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4731                 check_added_monitors!(nodes[0], 1);
4732
4733                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4734                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4735                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4736                 check_added_monitors!(nodes[0], 1);
4737                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4738                 check_added_monitors!(nodes[1], 1);
4739                 // AwaitingRemoteRevoke ends here
4740
4741                 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4742                 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
4743                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
4744                 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
4745                 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
4746                 assert_eq!(commitment_update.update_fee.is_none(), true);
4747
4748                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]).unwrap();
4749                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4750                 check_added_monitors!(nodes[0], 1);
4751                 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4752
4753                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke).unwrap();
4754                 check_added_monitors!(nodes[1], 1);
4755                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4756
4757                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed).unwrap();
4758                 check_added_monitors!(nodes[1], 1);
4759                 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4760                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4761
4762                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke).unwrap();
4763                 check_added_monitors!(nodes[0], 1);
4764                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4765
4766                 let events = nodes[0].node.get_and_clear_pending_events();
4767                 assert_eq!(events.len(), 1);
4768                 match events[0] {
4769                         Event::PendingHTLCsForwardable { .. } => { },
4770                         _ => panic!("Unexpected event"),
4771                 };
4772                 nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
4773                 nodes[0].node.process_pending_htlc_forwards();
4774
4775                 let events = nodes[0].node.get_and_clear_pending_events();
4776                 assert_eq!(events.len(), 1);
4777                 match events[0] {
4778                         Event::PaymentReceived { .. } => { },
4779                         _ => panic!("Unexpected event"),
4780                 };
4781
4782                 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
4783
4784                 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
4785                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
4786                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4787         }
4788
4789         #[test]
4790         fn test_update_fee() {
4791                 let nodes = create_network(2);
4792                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4793                 let channel_id = chan.2;
4794
4795                 // A                                        B
4796                 // (1) update_fee/commitment_signed      ->
4797                 //                                       <- (2) revoke_and_ack
4798                 //                                       .- send (3) commitment_signed
4799                 // (4) update_fee/commitment_signed      ->
4800                 //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
4801                 //                                       <- (3) commitment_signed delivered
4802                 // send (6) revoke_and_ack               -.
4803                 //                                       <- (5) deliver revoke_and_ack
4804                 // (6) deliver revoke_and_ack            ->
4805                 //                                       .- send (7) commitment_signed in response to (4)
4806                 //                                       <- (7) deliver commitment_signed
4807                 // revoke_and_ack                        ->
4808
4809                 // Create and deliver (1)...
4810                 let feerate = get_feerate!(nodes[0], channel_id);
4811                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4812                 check_added_monitors!(nodes[0], 1);
4813
4814                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4815                 assert_eq!(events_0.len(), 1);
4816                 let (update_msg, commitment_signed) = match events_0[0] {
4817                                 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 } } => {
4818                                 (update_fee.as_ref(), commitment_signed)
4819                         },
4820                         _ => panic!("Unexpected event"),
4821                 };
4822                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4823
4824                 // Generate (2) and (3):
4825                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4826                 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4827                 check_added_monitors!(nodes[1], 1);
4828
4829                 // Deliver (2):
4830                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4831                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4832                 check_added_monitors!(nodes[0], 1);
4833
4834                 // Create and deliver (4)...
4835                 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
4836                 check_added_monitors!(nodes[0], 1);
4837                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4838                 assert_eq!(events_0.len(), 1);
4839                 let (update_msg, commitment_signed) = match events_0[0] {
4840                                 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 } } => {
4841                                 (update_fee.as_ref(), commitment_signed)
4842                         },
4843                         _ => panic!("Unexpected event"),
4844                 };
4845
4846                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4847                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4848                 check_added_monitors!(nodes[1], 1);
4849                 // ... creating (5)
4850                 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4851                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4852
4853                 // Handle (3), creating (6):
4854                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0).unwrap();
4855                 check_added_monitors!(nodes[0], 1);
4856                 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4857                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4858
4859                 // Deliver (5):
4860                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4861                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4862                 check_added_monitors!(nodes[0], 1);
4863
4864                 // Deliver (6), creating (7):
4865                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0).unwrap();
4866                 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4867                 assert!(commitment_update.update_add_htlcs.is_empty());
4868                 assert!(commitment_update.update_fulfill_htlcs.is_empty());
4869                 assert!(commitment_update.update_fail_htlcs.is_empty());
4870                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
4871                 assert!(commitment_update.update_fee.is_none());
4872                 check_added_monitors!(nodes[1], 1);
4873
4874                 // Deliver (7)
4875                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4876                 check_added_monitors!(nodes[0], 1);
4877                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4878                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4879
4880                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4881                 check_added_monitors!(nodes[1], 1);
4882                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4883
4884                 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
4885                 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
4886                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4887         }
4888
4889         #[test]
4890         fn pre_funding_lock_shutdown_test() {
4891                 // Test sending a shutdown prior to funding_locked after funding generation
4892                 let nodes = create_network(2);
4893                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0);
4894                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4895                 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4896                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4897
4898                 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
4899                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4900                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4901                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4902                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4903
4904                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4905                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4906                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4907                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4908                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4909                 assert!(node_0_none.is_none());
4910
4911                 assert!(nodes[0].node.list_channels().is_empty());
4912                 assert!(nodes[1].node.list_channels().is_empty());
4913         }
4914
4915         #[test]
4916         fn updates_shutdown_wait() {
4917                 // Test sending a shutdown with outstanding updates pending
4918                 let mut nodes = create_network(3);
4919                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4920                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4921                 let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4922                 let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4923
4924                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
4925
4926                 nodes[0].node.close_channel(&chan_1.2).unwrap();
4927                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4928                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4929                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4930                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4931
4932                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4933                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4934
4935                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4936                 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route_1, payment_hash) {}
4937                 else { panic!("New sends should fail!") };
4938                 if let Err(APIError::ChannelUnavailable {..}) = nodes[1].node.send_payment(route_2, payment_hash) {}
4939                 else { panic!("New sends should fail!") };
4940
4941                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
4942                 check_added_monitors!(nodes[2], 1);
4943                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4944                 assert!(updates.update_add_htlcs.is_empty());
4945                 assert!(updates.update_fail_htlcs.is_empty());
4946                 assert!(updates.update_fail_malformed_htlcs.is_empty());
4947                 assert!(updates.update_fee.is_none());
4948                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4949                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
4950                 check_added_monitors!(nodes[1], 1);
4951                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4952                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
4953
4954                 assert!(updates_2.update_add_htlcs.is_empty());
4955                 assert!(updates_2.update_fail_htlcs.is_empty());
4956                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
4957                 assert!(updates_2.update_fee.is_none());
4958                 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
4959                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
4960                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
4961
4962                 let events = nodes[0].node.get_and_clear_pending_events();
4963                 assert_eq!(events.len(), 1);
4964                 match events[0] {
4965                         Event::PaymentSent { ref payment_preimage } => {
4966                                 assert_eq!(our_payment_preimage, *payment_preimage);
4967                         },
4968                         _ => panic!("Unexpected event"),
4969                 }
4970
4971                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4972                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4973                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4974                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4975                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4976                 assert!(node_0_none.is_none());
4977
4978                 assert!(nodes[0].node.list_channels().is_empty());
4979
4980                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4981                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
4982                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
4983                 assert!(nodes[1].node.list_channels().is_empty());
4984                 assert!(nodes[2].node.list_channels().is_empty());
4985         }
4986
4987         #[test]
4988         fn htlc_fail_async_shutdown() {
4989                 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
4990                 let mut nodes = create_network(3);
4991                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4992                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4993
4994                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4995                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4996                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
4997                 check_added_monitors!(nodes[0], 1);
4998                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4999                 assert_eq!(updates.update_add_htlcs.len(), 1);
5000                 assert!(updates.update_fulfill_htlcs.is_empty());
5001                 assert!(updates.update_fail_htlcs.is_empty());
5002                 assert!(updates.update_fail_malformed_htlcs.is_empty());
5003                 assert!(updates.update_fee.is_none());
5004
5005                 nodes[1].node.close_channel(&chan_1.2).unwrap();
5006                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5007                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
5008                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5009
5010                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5011                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
5012                 check_added_monitors!(nodes[1], 1);
5013                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
5014                 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
5015
5016                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5017                 assert!(updates_2.update_add_htlcs.is_empty());
5018                 assert!(updates_2.update_fulfill_htlcs.is_empty());
5019                 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
5020                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
5021                 assert!(updates_2.update_fee.is_none());
5022
5023                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]).unwrap();
5024                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
5025
5026                 let events = nodes[0].node.get_and_clear_pending_events();
5027                 assert_eq!(events.len(), 1);
5028                 match events[0] {
5029                         Event::PaymentFailed { ref payment_hash, ref rejected_by_dest } => {
5030                                 assert_eq!(our_payment_hash, *payment_hash);
5031                                 assert!(!rejected_by_dest);
5032                         },
5033                         _ => panic!("Unexpected event"),
5034                 }
5035
5036                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5037                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5038                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5039                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5040                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5041                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5042                 assert!(node_0_none.is_none());
5043
5044                 assert!(nodes[0].node.list_channels().is_empty());
5045
5046                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5047                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5048                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5049                 assert!(nodes[1].node.list_channels().is_empty());
5050                 assert!(nodes[2].node.list_channels().is_empty());
5051         }
5052
5053         fn do_test_shutdown_rebroadcast(recv_count: u8) {
5054                 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
5055                 // messages delivered prior to disconnect
5056                 let nodes = create_network(3);
5057                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5058                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5059
5060                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
5061
5062                 nodes[1].node.close_channel(&chan_1.2).unwrap();
5063                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5064                 if recv_count > 0 {
5065                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
5066                         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5067                         if recv_count > 1 {
5068                                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
5069                         }
5070                 }
5071
5072                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5073                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5074
5075                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5076                 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5077                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5078                 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5079
5080                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish).unwrap();
5081                 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5082                 assert!(node_1_shutdown == node_1_2nd_shutdown);
5083
5084                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish).unwrap();
5085                 let node_0_2nd_shutdown = if recv_count > 0 {
5086                         let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5087                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5088                         node_0_2nd_shutdown
5089                 } else {
5090                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5091                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5092                         get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
5093                 };
5094                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown).unwrap();
5095
5096                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5097                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5098
5099                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
5100                 check_added_monitors!(nodes[2], 1);
5101                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5102                 assert!(updates.update_add_htlcs.is_empty());
5103                 assert!(updates.update_fail_htlcs.is_empty());
5104                 assert!(updates.update_fail_malformed_htlcs.is_empty());
5105                 assert!(updates.update_fee.is_none());
5106                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5107                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
5108                 check_added_monitors!(nodes[1], 1);
5109                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5110                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
5111
5112                 assert!(updates_2.update_add_htlcs.is_empty());
5113                 assert!(updates_2.update_fail_htlcs.is_empty());
5114                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
5115                 assert!(updates_2.update_fee.is_none());
5116                 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
5117                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
5118                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
5119
5120                 let events = nodes[0].node.get_and_clear_pending_events();
5121                 assert_eq!(events.len(), 1);
5122                 match events[0] {
5123                         Event::PaymentSent { ref payment_preimage } => {
5124                                 assert_eq!(our_payment_preimage, *payment_preimage);
5125                         },
5126                         _ => panic!("Unexpected event"),
5127                 }
5128
5129                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5130                 if recv_count > 0 {
5131                         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5132                         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5133                         assert!(node_1_closing_signed.is_some());
5134                 }
5135
5136                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5137                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5138
5139                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5140                 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5141                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5142                 if recv_count == 0 {
5143                         // If all closing_signeds weren't delivered we can just resume where we left off...
5144                         let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5145
5146                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish).unwrap();
5147                         let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5148                         assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
5149
5150                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish).unwrap();
5151                         let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5152                         assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
5153
5154                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown).unwrap();
5155                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5156
5157                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown).unwrap();
5158                         let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5159                         assert!(node_0_closing_signed == node_0_2nd_closing_signed);
5160
5161                         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed).unwrap();
5162                         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5163                         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5164                         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5165                         assert!(node_0_none.is_none());
5166                 } else {
5167                         // If one node, however, received + responded with an identical closing_signed we end
5168                         // up erroring and node[0] will try to broadcast its own latest commitment transaction.
5169                         // There isn't really anything better we can do simply, but in the future we might
5170                         // explore storing a set of recently-closed channels that got disconnected during
5171                         // closing_signed and avoiding broadcasting local commitment txn for some timeout to
5172                         // give our counterparty enough time to (potentially) broadcast a cooperative closing
5173                         // transaction.
5174                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5175
5176                         if let Err(msgs::HandleError{action: Some(msgs::ErrorAction::SendErrorMessage{msg}), ..}) =
5177                                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish) {
5178                                 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
5179                                 let msgs::ErrorMessage {ref channel_id, ..} = msg;
5180                                 assert_eq!(*channel_id, chan_1.2);
5181                         } else { panic!("Needed SendErrorMessage close"); }
5182
5183                         // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
5184                         // checks it, but in this case nodes[0] didn't ever get a chance to receive a
5185                         // closing_signed so we do it ourselves
5186                         let events = nodes[0].node.get_and_clear_pending_msg_events();
5187                         assert_eq!(events.len(), 1);
5188                         match events[0] {
5189                                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5190                                         assert_eq!(msg.contents.flags & 2, 2);
5191                                 },
5192                                 _ => panic!("Unexpected event"),
5193                         }
5194                 }
5195
5196                 assert!(nodes[0].node.list_channels().is_empty());
5197
5198                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5199                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5200                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5201                 assert!(nodes[1].node.list_channels().is_empty());
5202                 assert!(nodes[2].node.list_channels().is_empty());
5203         }
5204
5205         #[test]
5206         fn test_shutdown_rebroadcast() {
5207                 do_test_shutdown_rebroadcast(0);
5208                 do_test_shutdown_rebroadcast(1);
5209                 do_test_shutdown_rebroadcast(2);
5210         }
5211
5212         #[test]
5213         fn fake_network_test() {
5214                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5215                 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
5216                 let nodes = create_network(4);
5217
5218                 // Create some initial channels
5219                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5220                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5221                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5222
5223                 // Rebalance the network a bit by relaying one payment through all the channels...
5224                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5225                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5226                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5227                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5228
5229                 // Send some more payments
5230                 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
5231                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
5232                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
5233
5234                 // Test failure packets
5235                 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
5236                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
5237
5238                 // Add a new channel that skips 3
5239                 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
5240
5241                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
5242                 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
5243                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5244                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5245                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5246                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5247                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5248
5249                 // Do some rebalance loop payments, simultaneously
5250                 let mut hops = Vec::with_capacity(3);
5251                 hops.push(RouteHop {
5252                         pubkey: nodes[2].node.get_our_node_id(),
5253                         short_channel_id: chan_2.0.contents.short_channel_id,
5254                         fee_msat: 0,
5255                         cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
5256                 });
5257                 hops.push(RouteHop {
5258                         pubkey: nodes[3].node.get_our_node_id(),
5259                         short_channel_id: chan_3.0.contents.short_channel_id,
5260                         fee_msat: 0,
5261                         cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
5262                 });
5263                 hops.push(RouteHop {
5264                         pubkey: nodes[1].node.get_our_node_id(),
5265                         short_channel_id: chan_4.0.contents.short_channel_id,
5266                         fee_msat: 1000000,
5267                         cltv_expiry_delta: TEST_FINAL_CLTV,
5268                 });
5269                 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;
5270                 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;
5271                 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
5272
5273                 let mut hops = Vec::with_capacity(3);
5274                 hops.push(RouteHop {
5275                         pubkey: nodes[3].node.get_our_node_id(),
5276                         short_channel_id: chan_4.0.contents.short_channel_id,
5277                         fee_msat: 0,
5278                         cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
5279                 });
5280                 hops.push(RouteHop {
5281                         pubkey: nodes[2].node.get_our_node_id(),
5282                         short_channel_id: chan_3.0.contents.short_channel_id,
5283                         fee_msat: 0,
5284                         cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
5285                 });
5286                 hops.push(RouteHop {
5287                         pubkey: nodes[1].node.get_our_node_id(),
5288                         short_channel_id: chan_2.0.contents.short_channel_id,
5289                         fee_msat: 1000000,
5290                         cltv_expiry_delta: TEST_FINAL_CLTV,
5291                 });
5292                 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;
5293                 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;
5294                 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
5295
5296                 // Claim the rebalances...
5297                 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
5298                 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
5299
5300                 // Add a duplicate new channel from 2 to 4
5301                 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3);
5302
5303                 // Send some payments across both channels
5304                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5305                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5306                 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5307
5308                 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
5309
5310                 //TODO: Test that routes work again here as we've been notified that the channel is full
5311
5312                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
5313                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
5314                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
5315
5316                 // Close down the channels...
5317                 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
5318                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
5319                 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
5320                 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
5321                 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
5322         }
5323
5324         #[test]
5325         fn duplicate_htlc_test() {
5326                 // Test that we accept duplicate payment_hash HTLCs across the network and that
5327                 // claiming/failing them are all separate and don't effect each other
5328                 let mut nodes = create_network(6);
5329
5330                 // Create some initial channels to route via 3 to 4/5 from 0/1/2
5331                 create_announced_chan_between_nodes(&nodes, 0, 3);
5332                 create_announced_chan_between_nodes(&nodes, 1, 3);
5333                 create_announced_chan_between_nodes(&nodes, 2, 3);
5334                 create_announced_chan_between_nodes(&nodes, 3, 4);
5335                 create_announced_chan_between_nodes(&nodes, 3, 5);
5336
5337                 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
5338
5339                 *nodes[0].network_payment_count.borrow_mut() -= 1;
5340                 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
5341
5342                 *nodes[0].network_payment_count.borrow_mut() -= 1;
5343                 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
5344
5345                 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
5346                 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
5347                 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
5348         }
5349
5350         #[derive(PartialEq)]
5351         enum HTLCType { NONE, TIMEOUT, SUCCESS }
5352         /// Tests that the given node has broadcast transactions for the given Channel
5353         ///
5354         /// First checks that the latest local commitment tx has been broadcast, unless an explicit
5355         /// commitment_tx is provided, which may be used to test that a remote commitment tx was
5356         /// broadcast and the revoked outputs were claimed.
5357         ///
5358         /// Next tests that there is (or is not) a transaction that spends the commitment transaction
5359         /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
5360         ///
5361         /// All broadcast transactions must be accounted for in one of the above three types of we'll
5362         /// also fail.
5363         fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
5364                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5365                 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
5366
5367                 let mut res = Vec::with_capacity(2);
5368                 node_txn.retain(|tx| {
5369                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
5370                                 check_spends!(tx, chan.3.clone());
5371                                 if commitment_tx.is_none() {
5372                                         res.push(tx.clone());
5373                                 }
5374                                 false
5375                         } else { true }
5376                 });
5377                 if let Some(explicit_tx) = commitment_tx {
5378                         res.push(explicit_tx.clone());
5379                 }
5380
5381                 assert_eq!(res.len(), 1);
5382
5383                 if has_htlc_tx != HTLCType::NONE {
5384                         node_txn.retain(|tx| {
5385                                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
5386                                         check_spends!(tx, res[0].clone());
5387                                         if has_htlc_tx == HTLCType::TIMEOUT {
5388                                                 assert!(tx.lock_time != 0);
5389                                         } else {
5390                                                 assert!(tx.lock_time == 0);
5391                                         }
5392                                         res.push(tx.clone());
5393                                         false
5394                                 } else { true }
5395                         });
5396                         assert!(res.len() == 2 || res.len() == 3);
5397                         if res.len() == 3 {
5398                                 assert_eq!(res[1], res[2]);
5399                         }
5400                 }
5401
5402                 assert!(node_txn.is_empty());
5403                 res
5404         }
5405
5406         /// Tests that the given node has broadcast a claim transaction against the provided revoked
5407         /// HTLC transaction.
5408         fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
5409                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5410                 assert_eq!(node_txn.len(), 1);
5411                 node_txn.retain(|tx| {
5412                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
5413                                 check_spends!(tx, revoked_tx.clone());
5414                                 false
5415                         } else { true }
5416                 });
5417                 assert!(node_txn.is_empty());
5418         }
5419
5420         fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
5421                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5422
5423                 assert!(node_txn.len() >= 1);
5424                 assert_eq!(node_txn[0].input.len(), 1);
5425                 let mut found_prev = false;
5426
5427                 for tx in prev_txn {
5428                         if node_txn[0].input[0].previous_output.txid == tx.txid() {
5429                                 check_spends!(node_txn[0], tx.clone());
5430                                 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
5431                                 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
5432
5433                                 found_prev = true;
5434                                 break;
5435                         }
5436                 }
5437                 assert!(found_prev);
5438
5439                 let mut res = Vec::new();
5440                 mem::swap(&mut *node_txn, &mut res);
5441                 res
5442         }
5443
5444         fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
5445                 let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
5446                 assert_eq!(events_1.len(), 1);
5447                 let as_update = match events_1[0] {
5448                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5449                                 msg.clone()
5450                         },
5451                         _ => panic!("Unexpected event"),
5452                 };
5453
5454                 let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
5455                 assert_eq!(events_2.len(), 1);
5456                 let bs_update = match events_2[0] {
5457                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5458                                 msg.clone()
5459                         },
5460                         _ => panic!("Unexpected event"),
5461                 };
5462
5463                 for node in nodes {
5464                         node.router.handle_channel_update(&as_update).unwrap();
5465                         node.router.handle_channel_update(&bs_update).unwrap();
5466                 }
5467         }
5468
5469         macro_rules! expect_pending_htlcs_forwardable {
5470                 ($node: expr) => {{
5471                         let events = $node.node.get_and_clear_pending_events();
5472                         assert_eq!(events.len(), 1);
5473                         match events[0] {
5474                                 Event::PendingHTLCsForwardable { .. } => { },
5475                                 _ => panic!("Unexpected event"),
5476                         };
5477                         $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
5478                         $node.node.process_pending_htlc_forwards();
5479                 }}
5480         }
5481
5482         fn do_channel_reserve_test(test_recv: bool) {
5483                 use util::rng;
5484                 use std::sync::atomic::Ordering;
5485                 use ln::msgs::HandleError;
5486
5487                 macro_rules! get_channel_value_stat {
5488                         ($node: expr, $channel_id: expr) => {{
5489                                 let chan_lock = $node.node.channel_state.lock().unwrap();
5490                                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
5491                                 chan.get_value_stat()
5492                         }}
5493                 }
5494
5495                 let mut nodes = create_network(3);
5496                 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001);
5497                 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001);
5498
5499                 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
5500                 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
5501
5502                 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
5503                 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
5504
5505                 macro_rules! get_route_and_payment_hash {
5506                         ($recv_value: expr) => {{
5507                                 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
5508                                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5509                                 (route, payment_hash, payment_preimage)
5510                         }}
5511                 };
5512
5513                 macro_rules! expect_forward {
5514                         ($node: expr) => {{
5515                                 let mut events = $node.node.get_and_clear_pending_msg_events();
5516                                 assert_eq!(events.len(), 1);
5517                                 check_added_monitors!($node, 1);
5518                                 let payment_event = SendEvent::from_event(events.remove(0));
5519                                 payment_event
5520                         }}
5521                 }
5522
5523                 macro_rules! expect_payment_received {
5524                         ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
5525                                 let events = $node.node.get_and_clear_pending_events();
5526                                 assert_eq!(events.len(), 1);
5527                                 match events[0] {
5528                                         Event::PaymentReceived { ref payment_hash, amt } => {
5529                                                 assert_eq!($expected_payment_hash, *payment_hash);
5530                                                 assert_eq!($expected_recv_value, amt);
5531                                         },
5532                                         _ => panic!("Unexpected event"),
5533                                 }
5534                         }
5535                 };
5536
5537                 let feemsat = 239; // somehow we know?
5538                 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
5539
5540                 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
5541
5542                 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
5543                 {
5544                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
5545                         assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
5546                         let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
5547                         match err {
5548                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
5549                                 _ => panic!("Unknown error variants"),
5550                         }
5551                 }
5552
5553                 let mut htlc_id = 0;
5554                 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
5555                 // nodes[0]'s wealth
5556                 loop {
5557                         let amt_msat = recv_value_0 + total_fee_msat;
5558                         if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
5559                                 break;
5560                         }
5561                         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
5562                         htlc_id += 1;
5563
5564                         let (stat01_, stat11_, stat12_, stat22_) = (
5565                                 get_channel_value_stat!(nodes[0], chan_1.2),
5566                                 get_channel_value_stat!(nodes[1], chan_1.2),
5567                                 get_channel_value_stat!(nodes[1], chan_2.2),
5568                                 get_channel_value_stat!(nodes[2], chan_2.2),
5569                         );
5570
5571                         assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
5572                         assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
5573                         assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
5574                         assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
5575                         stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
5576                 }
5577
5578                 {
5579                         let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
5580                         // attempt to get channel_reserve violation
5581                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
5582                         let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
5583                         match err {
5584                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5585                                 _ => panic!("Unknown error variants"),
5586                         }
5587                 }
5588
5589                 // adding pending output
5590                 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
5591                 let amt_msat_1 = recv_value_1 + total_fee_msat;
5592
5593                 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
5594                 let payment_event_1 = {
5595                         nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
5596                         check_added_monitors!(nodes[0], 1);
5597
5598                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5599                         assert_eq!(events.len(), 1);
5600                         SendEvent::from_event(events.remove(0))
5601                 };
5602                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]).unwrap();
5603
5604                 // channel reserve test with htlc pending output > 0
5605                 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
5606                 {
5607                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5608                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5609                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5610                                 _ => panic!("Unknown error variants"),
5611                         }
5612                 }
5613
5614                 {
5615                         // test channel_reserve test on nodes[1] side
5616                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5617
5618                         // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
5619                         let secp_ctx = Secp256k1::new();
5620                         let session_priv = SecretKey::from_slice(&secp_ctx, &{
5621                                 let mut session_key = [0; 32];
5622                                 rng::fill_bytes(&mut session_key);
5623                                 session_key
5624                         }).expect("RNG is bad!");
5625
5626                         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5627                         let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
5628                         let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height).unwrap();
5629                         let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
5630                         let msg = msgs::UpdateAddHTLC {
5631                                 channel_id: chan_1.2,
5632                                 htlc_id,
5633                                 amount_msat: htlc_msat,
5634                                 payment_hash: our_payment_hash,
5635                                 cltv_expiry: htlc_cltv,
5636                                 onion_routing_packet: onion_packet,
5637                         };
5638
5639                         if test_recv {
5640                                 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).err().unwrap();
5641                                 match err {
5642                                         HandleError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
5643                                 }
5644                                 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
5645                                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5646                                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5647                                 let channel_close_broadcast = nodes[1].node.get_and_clear_pending_msg_events();
5648                                 assert_eq!(channel_close_broadcast.len(), 1);
5649                                 match channel_close_broadcast[0] {
5650                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5651                                                 assert_eq!(msg.contents.flags & 2, 2);
5652                                         },
5653                                         _ => panic!("Unexpected event"),
5654                                 }
5655                                 return;
5656                         }
5657                 }
5658
5659                 // split the rest to test holding cell
5660                 let recv_value_21 = recv_value_2/2;
5661                 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
5662                 {
5663                         let stat = get_channel_value_stat!(nodes[0], chan_1.2);
5664                         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);
5665                 }
5666
5667                 // now see if they go through on both sides
5668                 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
5669                 // but this will stuck in the holding cell
5670                 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
5671                 check_added_monitors!(nodes[0], 0);
5672                 let events = nodes[0].node.get_and_clear_pending_events();
5673                 assert_eq!(events.len(), 0);
5674
5675                 // test with outbound holding cell amount > 0
5676                 {
5677                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
5678                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5679                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5680                                 _ => panic!("Unknown error variants"),
5681                         }
5682                 }
5683
5684                 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
5685                 // this will also stuck in the holding cell
5686                 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
5687                 check_added_monitors!(nodes[0], 0);
5688                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
5689                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5690
5691                 // flush the pending htlc
5692                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg).unwrap();
5693                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5694                 check_added_monitors!(nodes[1], 1);
5695
5696                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
5697                 check_added_monitors!(nodes[0], 1);
5698                 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5699
5700                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed).unwrap();
5701                 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
5702                 // No commitment_signed so get_event_msg's assert(len == 1) passes
5703                 check_added_monitors!(nodes[0], 1);
5704
5705                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
5706                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5707                 check_added_monitors!(nodes[1], 1);
5708
5709                 expect_pending_htlcs_forwardable!(nodes[1]);
5710
5711                 let ref payment_event_11 = expect_forward!(nodes[1]);
5712                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]).unwrap();
5713                 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
5714
5715                 expect_pending_htlcs_forwardable!(nodes[2]);
5716                 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
5717
5718                 // flush the htlcs in the holding cell
5719                 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
5720                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]).unwrap();
5721                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]).unwrap();
5722                 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
5723                 expect_pending_htlcs_forwardable!(nodes[1]);
5724
5725                 let ref payment_event_3 = expect_forward!(nodes[1]);
5726                 assert_eq!(payment_event_3.msgs.len(), 2);
5727                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]).unwrap();
5728                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]).unwrap();
5729
5730                 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
5731                 expect_pending_htlcs_forwardable!(nodes[2]);
5732
5733                 let events = nodes[2].node.get_and_clear_pending_events();
5734                 assert_eq!(events.len(), 2);
5735                 match events[0] {
5736                         Event::PaymentReceived { ref payment_hash, amt } => {
5737                                 assert_eq!(our_payment_hash_21, *payment_hash);
5738                                 assert_eq!(recv_value_21, amt);
5739                         },
5740                         _ => panic!("Unexpected event"),
5741                 }
5742                 match events[1] {
5743                         Event::PaymentReceived { ref payment_hash, amt } => {
5744                                 assert_eq!(our_payment_hash_22, *payment_hash);
5745                                 assert_eq!(recv_value_22, amt);
5746                         },
5747                         _ => panic!("Unexpected event"),
5748                 }
5749
5750                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
5751                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
5752                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
5753
5754                 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);
5755                 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
5756                 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
5757                 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
5758
5759                 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
5760                 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
5761         }
5762
5763         #[test]
5764         fn channel_reserve_test() {
5765                 do_channel_reserve_test(false);
5766                 do_channel_reserve_test(true);
5767         }
5768
5769         #[test]
5770         fn channel_monitor_network_test() {
5771                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5772                 // tests that ChannelMonitor is able to recover from various states.
5773                 let nodes = create_network(5);
5774
5775                 // Create some initial channels
5776                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5777                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5778                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5779                 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5780
5781                 // Rebalance the network a bit by relaying one payment through all the channels...
5782                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5783                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5784                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5785                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5786
5787                 // Simple case with no pending HTLCs:
5788                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
5789                 {
5790                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
5791                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5792                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5793                         test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
5794                 }
5795                 get_announce_close_broadcast_events(&nodes, 0, 1);
5796                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5797                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5798
5799                 // One pending HTLC is discarded by the force-close:
5800                 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
5801
5802                 // Simple case of one pending HTLC to HTLC-Timeout
5803                 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
5804                 {
5805                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
5806                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5807                         nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5808                         test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
5809                 }
5810                 get_announce_close_broadcast_events(&nodes, 1, 2);
5811                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5812                 assert_eq!(nodes[2].node.list_channels().len(), 1);
5813
5814                 macro_rules! claim_funds {
5815                         ($node: expr, $prev_node: expr, $preimage: expr) => {
5816                                 {
5817                                         assert!($node.node.claim_funds($preimage));
5818                                         check_added_monitors!($node, 1);
5819
5820                                         let events = $node.node.get_and_clear_pending_msg_events();
5821                                         assert_eq!(events.len(), 1);
5822                                         match events[0] {
5823                                                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
5824                                                         assert!(update_add_htlcs.is_empty());
5825                                                         assert!(update_fail_htlcs.is_empty());
5826                                                         assert_eq!(*node_id, $prev_node.node.get_our_node_id());
5827                                                 },
5828                                                 _ => panic!("Unexpected event"),
5829                                         };
5830                                 }
5831                         }
5832                 }
5833
5834                 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
5835                 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
5836                 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
5837                 {
5838                         let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
5839
5840                         // Claim the payment on nodes[3], giving it knowledge of the preimage
5841                         claim_funds!(nodes[3], nodes[2], payment_preimage_1);
5842
5843                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5844                         nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
5845
5846                         check_preimage_claim(&nodes[3], &node_txn);
5847                 }
5848                 get_announce_close_broadcast_events(&nodes, 2, 3);
5849                 assert_eq!(nodes[2].node.list_channels().len(), 0);
5850                 assert_eq!(nodes[3].node.list_channels().len(), 1);
5851
5852                 { // Cheat and reset nodes[4]'s height to 1
5853                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5854                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![] }, 1);
5855                 }
5856
5857                 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
5858                 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
5859                 // One pending HTLC to time out:
5860                 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
5861                 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
5862                 // buffer space).
5863
5864                 {
5865                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5866                         nodes[3].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5867                         for i in 3..TEST_FINAL_CLTV + 2 + HTLC_FAIL_TIMEOUT_BLOCKS + 1 {
5868                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5869                                 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5870                         }
5871
5872                         let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
5873
5874                         // Claim the payment on nodes[4], giving it knowledge of the preimage
5875                         claim_funds!(nodes[4], nodes[3], payment_preimage_2);
5876
5877                         header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5878                         nodes[4].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5879                         for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
5880                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5881                                 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5882                         }
5883
5884                         test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
5885
5886                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5887                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
5888
5889                         check_preimage_claim(&nodes[4], &node_txn);
5890                 }
5891                 get_announce_close_broadcast_events(&nodes, 3, 4);
5892                 assert_eq!(nodes[3].node.list_channels().len(), 0);
5893                 assert_eq!(nodes[4].node.list_channels().len(), 0);
5894         }
5895
5896         #[test]
5897         fn test_justice_tx() {
5898                 // Test justice txn built on revoked HTLC-Success tx, against both sides
5899
5900                 let nodes = create_network(2);
5901                 // Create some new channels:
5902                 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
5903
5904                 // A pending HTLC which will be revoked:
5905                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5906                 // Get the will-be-revoked local txn from nodes[0]
5907                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5908                 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
5909                 assert_eq!(revoked_local_txn[0].input.len(), 1);
5910                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
5911                 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
5912                 assert_eq!(revoked_local_txn[1].input.len(), 1);
5913                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
5914                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
5915                 // Revoke the old state
5916                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
5917
5918                 {
5919                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5920                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5921                         {
5922                                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5923                                 assert_eq!(node_txn.len(), 3);
5924                                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5925                                 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
5926
5927                                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5928                                 node_txn.swap_remove(0);
5929                         }
5930                         test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
5931
5932                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5933                         let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
5934                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5935                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5936                         test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
5937                 }
5938                 get_announce_close_broadcast_events(&nodes, 0, 1);
5939
5940                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5941                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5942
5943                 // We test justice_tx build by A on B's revoked HTLC-Success tx
5944                 // Create some new channels:
5945                 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
5946
5947                 // A pending HTLC which will be revoked:
5948                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5949                 // Get the will-be-revoked local txn from B
5950                 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5951                 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
5952                 assert_eq!(revoked_local_txn[0].input.len(), 1);
5953                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
5954                 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
5955                 // Revoke the old state
5956                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
5957                 {
5958                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5959                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5960                         {
5961                                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5962                                 assert_eq!(node_txn.len(), 3);
5963                                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5964                                 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
5965
5966                                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5967                                 node_txn.swap_remove(0);
5968                         }
5969                         test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
5970
5971                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5972                         let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
5973                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5974                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5975                         test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone());
5976                 }
5977                 get_announce_close_broadcast_events(&nodes, 0, 1);
5978                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5979                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5980         }
5981
5982         #[test]
5983         fn revoked_output_claim() {
5984                 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
5985                 // transaction is broadcast by its counterparty
5986                 let nodes = create_network(2);
5987                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5988                 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
5989                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5990                 assert_eq!(revoked_local_txn.len(), 1);
5991                 // Only output is the full channel value back to nodes[0]:
5992                 assert_eq!(revoked_local_txn[0].output.len(), 1);
5993                 // Send a payment through, updating everyone's latest commitment txn
5994                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
5995
5996                 // Inform nodes[1] that nodes[0] broadcast a stale tx
5997                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5998                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5999                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6000                 assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
6001
6002                 assert_eq!(node_txn[0], node_txn[2]);
6003
6004                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
6005                 check_spends!(node_txn[1], chan_1.3.clone());
6006
6007                 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
6008                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6009                 get_announce_close_broadcast_events(&nodes, 0, 1);
6010         }
6011
6012         #[test]
6013         fn claim_htlc_outputs_shared_tx() {
6014                 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
6015                 let nodes = create_network(2);
6016
6017                 // Create some new channel:
6018                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6019
6020                 // Rebalance the network to generate htlc in the two directions
6021                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6022                 // 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
6023                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6024                 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6025
6026                 // Get the will-be-revoked local txn from node[0]
6027                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6028                 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
6029                 assert_eq!(revoked_local_txn[0].input.len(), 1);
6030                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
6031                 assert_eq!(revoked_local_txn[1].input.len(), 1);
6032                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
6033                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
6034                 check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
6035
6036                 //Revoke the old state
6037                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6038
6039                 {
6040                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6041                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6042                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6043
6044                         let events = nodes[1].node.get_and_clear_pending_events();
6045                         assert_eq!(events.len(), 1);
6046                         match events[0] {
6047                                 Event::PaymentFailed { payment_hash, .. } => {
6048                                         assert_eq!(payment_hash, payment_hash_2);
6049                                 },
6050                                 _ => panic!("Unexpected event"),
6051                         }
6052
6053                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6054                         assert_eq!(node_txn.len(), 4);
6055
6056                         assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
6057                         check_spends!(node_txn[0], revoked_local_txn[0].clone());
6058
6059                         assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
6060
6061                         let mut witness_lens = BTreeSet::new();
6062                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6063                         witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
6064                         witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
6065                         assert_eq!(witness_lens.len(), 3);
6066                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6067                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
6068                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
6069
6070                         // Next nodes[1] broadcasts its current local tx state:
6071                         assert_eq!(node_txn[1].input.len(), 1);
6072                         assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
6073
6074                         assert_eq!(node_txn[2].input.len(), 1);
6075                         let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
6076                         assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
6077                         assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
6078                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6079                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
6080                 }
6081                 get_announce_close_broadcast_events(&nodes, 0, 1);
6082                 assert_eq!(nodes[0].node.list_channels().len(), 0);
6083                 assert_eq!(nodes[1].node.list_channels().len(), 0);
6084         }
6085
6086         #[test]
6087         fn claim_htlc_outputs_single_tx() {
6088                 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
6089                 let nodes = create_network(2);
6090
6091                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6092
6093                 // Rebalance the network to generate htlc in the two directions
6094                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6095                 // 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
6096                 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
6097                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6098                 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6099
6100                 // Get the will-be-revoked local txn from node[0]
6101                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6102
6103                 //Revoke the old state
6104                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6105
6106                 {
6107                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6108                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6109                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6110
6111                         let events = nodes[1].node.get_and_clear_pending_events();
6112                         assert_eq!(events.len(), 1);
6113                         match events[0] {
6114                                 Event::PaymentFailed { payment_hash, .. } => {
6115                                         assert_eq!(payment_hash, payment_hash_2);
6116                                 },
6117                                 _ => panic!("Unexpected event"),
6118                         }
6119
6120                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6121                         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)
6122
6123                         assert_eq!(node_txn[0], node_txn[7]);
6124                         assert_eq!(node_txn[1], node_txn[8]);
6125                         assert_eq!(node_txn[2], node_txn[9]);
6126                         assert_eq!(node_txn[3], node_txn[10]);
6127                         assert_eq!(node_txn[4], node_txn[11]);
6128                         assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcated by ChannelManger
6129                         assert_eq!(node_txn[4], node_txn[6]);
6130
6131                         assert_eq!(node_txn[0].input.len(), 1);
6132                         assert_eq!(node_txn[1].input.len(), 1);
6133                         assert_eq!(node_txn[2].input.len(), 1);
6134
6135                         let mut revoked_tx_map = HashMap::new();
6136                         revoked_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
6137                         node_txn[0].verify(&revoked_tx_map).unwrap();
6138                         node_txn[1].verify(&revoked_tx_map).unwrap();
6139                         node_txn[2].verify(&revoked_tx_map).unwrap();
6140
6141                         let mut witness_lens = BTreeSet::new();
6142                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6143                         witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
6144                         witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
6145                         assert_eq!(witness_lens.len(), 3);
6146                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6147                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
6148                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
6149
6150                         assert_eq!(node_txn[3].input.len(), 1);
6151                         check_spends!(node_txn[3], chan_1.3.clone());
6152
6153                         assert_eq!(node_txn[4].input.len(), 1);
6154                         let witness_script = node_txn[4].input[0].witness.last().unwrap();
6155                         assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
6156                         assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
6157                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6158                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
6159                 }
6160                 get_announce_close_broadcast_events(&nodes, 0, 1);
6161                 assert_eq!(nodes[0].node.list_channels().len(), 0);
6162                 assert_eq!(nodes[1].node.list_channels().len(), 0);
6163         }
6164
6165         #[test]
6166         fn test_htlc_on_chain_success() {
6167                 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
6168                 // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
6169                 // broadcasting the right event to other nodes in payment path.
6170                 // A --------------------> B ----------------------> C (preimage)
6171                 // First, C should claim the HTLC output via HTLC-Success when its own latest local
6172                 // commitment transaction was broadcast.
6173                 // Then, B should learn the preimage from said transactions, attempting to claim backwards
6174                 // towards B.
6175                 // B should be able to claim via preimage if A then broadcasts its local tx.
6176                 // Finally, when A sees B's latest local commitment transaction it should be able to claim
6177                 // the HTLC output via the preimage it learned (which, once confirmed should generate a
6178                 // PaymentSent event).
6179
6180                 let nodes = create_network(3);
6181
6182                 // Create some initial channels
6183                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6184                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6185
6186                 // Rebalance the network a bit by relaying one payment through all the channels...
6187                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6188                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6189
6190                 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
6191                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6192
6193                 // Broadcast legit commitment tx from C on B's chain
6194                 // Broadcast HTLC Success transation by C on received output from C's commitment tx on B's chain
6195                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6196                 assert_eq!(commitment_tx.len(), 1);
6197                 check_spends!(commitment_tx[0], chan_2.3.clone());
6198                 nodes[2].node.claim_funds(our_payment_preimage);
6199                 check_added_monitors!(nodes[2], 1);
6200                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6201                 assert!(updates.update_add_htlcs.is_empty());
6202                 assert!(updates.update_fail_htlcs.is_empty());
6203                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6204                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
6205
6206                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6207                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6208                 assert_eq!(events.len(), 1);
6209                 match events[0] {
6210                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6211                         _ => panic!("Unexpected event"),
6212                 }
6213                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
6214                 assert_eq!(node_txn.len(), 3);
6215                 assert_eq!(node_txn[1], commitment_tx[0]);
6216                 assert_eq!(node_txn[0], node_txn[2]);
6217                 check_spends!(node_txn[0], commitment_tx[0].clone());
6218                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6219                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6220                 assert_eq!(node_txn[0].lock_time, 0);
6221
6222                 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
6223                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: node_txn}, 1);
6224                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6225                 {
6226                         let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
6227                         assert_eq!(added_monitors.len(), 1);
6228                         assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
6229                         added_monitors.clear();
6230                 }
6231                 assert_eq!(events.len(), 2);
6232                 match events[0] {
6233                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6234                         _ => panic!("Unexpected event"),
6235                 }
6236                 match events[1] {
6237                         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, .. } } => {
6238                                 assert!(update_add_htlcs.is_empty());
6239                                 assert!(update_fail_htlcs.is_empty());
6240                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6241                                 assert!(update_fail_malformed_htlcs.is_empty());
6242                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6243                         },
6244                         _ => panic!("Unexpected event"),
6245                 };
6246                 {
6247                         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
6248                         // commitment transaction with a corresponding HTLC-Timeout transaction, as well as a
6249                         // timeout-claim of the output that nodes[2] just claimed via success.
6250                         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)
6251                         assert_eq!(node_txn.len(), 4);
6252                         assert_eq!(node_txn[0], node_txn[3]);
6253                         check_spends!(node_txn[0], commitment_tx[0].clone());
6254                         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6255                         assert_ne!(node_txn[0].lock_time, 0);
6256                         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
6257                         check_spends!(node_txn[1], chan_2.3.clone());
6258                         check_spends!(node_txn[2], node_txn[1].clone());
6259                         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6260                         assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6261                         assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6262                         assert_ne!(node_txn[2].lock_time, 0);
6263                         node_txn.clear();
6264                 }
6265
6266                 // Broadcast legit commitment tx from A on B's chain
6267                 // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
6268                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6269                 check_spends!(commitment_tx[0], chan_1.3.clone());
6270                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6271                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6272                 assert_eq!(events.len(), 1);
6273                 match events[0] {
6274                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6275                         _ => panic!("Unexpected event"),
6276                 }
6277                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 1 (HTLC-Success) * 2 (block-rescan)
6278                 assert_eq!(node_txn.len(), 3);
6279                 assert_eq!(node_txn[0], node_txn[2]);
6280                 check_spends!(node_txn[0], commitment_tx[0].clone());
6281                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6282                 assert_eq!(node_txn[0].lock_time, 0);
6283                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
6284                 check_spends!(node_txn[1], chan_1.3.clone());
6285                 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6286                 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
6287                 // we already checked the same situation with A.
6288
6289                 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
6290                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
6291                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6292                 assert_eq!(events.len(), 1);
6293                 match events[0] {
6294                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6295                         _ => panic!("Unexpected event"),
6296                 }
6297                 let events = nodes[0].node.get_and_clear_pending_events();
6298                 assert_eq!(events.len(), 1);
6299                 match events[0] {
6300                         Event::PaymentSent { payment_preimage } => {
6301                                 assert_eq!(payment_preimage, our_payment_preimage);
6302                         },
6303                         _ => panic!("Unexpected event"),
6304                 }
6305                 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)
6306                 assert_eq!(node_txn.len(), 4);
6307                 assert_eq!(node_txn[0], node_txn[3]);
6308                 check_spends!(node_txn[0], commitment_tx[0].clone());
6309                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6310                 assert_ne!(node_txn[0].lock_time, 0);
6311                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6312                 check_spends!(node_txn[1], chan_1.3.clone());
6313                 check_spends!(node_txn[2], node_txn[1].clone());
6314                 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6315                 assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6316                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6317                 assert_ne!(node_txn[2].lock_time, 0);
6318         }
6319
6320         #[test]
6321         fn test_htlc_on_chain_timeout() {
6322                 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
6323                 // ChainWatchInterface and timeout the HTLC  bacward accordingly. So here we test that ChannelManager is
6324                 // broadcasting the right event to other nodes in payment path.
6325                 // A ------------------> B ----------------------> C (timeout)
6326                 //    B's commitment tx                 C's commitment tx
6327                 //            \                                  \
6328                 //         B's HTLC timeout tx               B's timeout tx
6329
6330                 let nodes = create_network(3);
6331
6332                 // Create some intial channels
6333                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6334                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6335
6336                 // Rebalance the network a bit by relaying one payment thorugh all the channels...
6337                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6338                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6339
6340                 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
6341                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6342
6343                 // Brodacast legit commitment tx from C on B's chain
6344                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6345                 check_spends!(commitment_tx[0], chan_2.3.clone());
6346                 nodes[2].node.fail_htlc_backwards(&payment_hash, PaymentFailReason::PreimageUnknown);
6347                 {
6348                         let mut added_monitors = nodes[2].chan_monitor.added_monitors.lock().unwrap();
6349                         assert_eq!(added_monitors.len(), 1);
6350                         added_monitors.clear();
6351                 }
6352                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6353                 assert_eq!(events.len(), 1);
6354                 match events[0] {
6355                         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, .. } } => {
6356                                 assert!(update_add_htlcs.is_empty());
6357                                 assert!(!update_fail_htlcs.is_empty());
6358                                 assert!(update_fulfill_htlcs.is_empty());
6359                                 assert!(update_fail_malformed_htlcs.is_empty());
6360                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
6361                         },
6362                         _ => panic!("Unexpected event"),
6363                 };
6364                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6365                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6366                 assert_eq!(events.len(), 1);
6367                 match events[0] {
6368                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6369                         _ => panic!("Unexpected event"),
6370                 }
6371                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
6372                 assert_eq!(node_txn.len(), 1);
6373                 check_spends!(node_txn[0], chan_2.3.clone());
6374                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
6375
6376                 // Broadcast timeout transaction by B on received output fron C's commitment tx on B's chain
6377                 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
6378                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6379                 let timeout_tx;
6380                 {
6381                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6382                         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)
6383                         assert_eq!(node_txn[0], node_txn[5]);
6384                         assert_eq!(node_txn[1], node_txn[6]);
6385                         assert_eq!(node_txn[2], node_txn[7]);
6386                         check_spends!(node_txn[0], commitment_tx[0].clone());
6387                         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6388                         check_spends!(node_txn[1], chan_2.3.clone());
6389                         check_spends!(node_txn[2], node_txn[1].clone());
6390                         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6391                         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6392                         check_spends!(node_txn[3], chan_2.3.clone());
6393                         check_spends!(node_txn[4], node_txn[3].clone());
6394                         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
6395                         assert_eq!(node_txn[4].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6396                         timeout_tx = node_txn[0].clone();
6397                         node_txn.clear();
6398                 }
6399
6400                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![timeout_tx]}, 1);
6401                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6402                 check_added_monitors!(nodes[1], 1);
6403                 assert_eq!(events.len(), 2);
6404                 match events[0] {
6405                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6406                         _ => panic!("Unexpected event"),
6407                 }
6408                 match events[1] {
6409                         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, .. } } => {
6410                                 assert!(update_add_htlcs.is_empty());
6411                                 assert!(!update_fail_htlcs.is_empty());
6412                                 assert!(update_fulfill_htlcs.is_empty());
6413                                 assert!(update_fail_malformed_htlcs.is_empty());
6414                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6415                         },
6416                         _ => panic!("Unexpected event"),
6417                 };
6418                 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
6419                 assert_eq!(node_txn.len(), 0);
6420
6421                 // Broadcast legit commitment tx from B on A's chain
6422                 let commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6423                 check_spends!(commitment_tx[0], chan_1.3.clone());
6424
6425                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6426                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6427                 assert_eq!(events.len(), 1);
6428                 match events[0] {
6429                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6430                         _ => panic!("Unexpected event"),
6431                 }
6432                 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
6433                 assert_eq!(node_txn.len(), 4);
6434                 assert_eq!(node_txn[0], node_txn[3]);
6435                 check_spends!(node_txn[0], commitment_tx[0].clone());
6436                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6437                 check_spends!(node_txn[1], chan_1.3.clone());
6438                 check_spends!(node_txn[2], node_txn[1].clone());
6439                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6440                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6441         }
6442
6443         #[test]
6444         fn test_simple_commitment_revoked_fail_backward() {
6445                 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
6446                 // and fail backward accordingly.
6447
6448                 let nodes = create_network(3);
6449
6450                 // Create some initial channels
6451                 create_announced_chan_between_nodes(&nodes, 0, 1);
6452                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6453
6454                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6455                 // Get the will-be-revoked local txn from nodes[2]
6456                 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6457                 // Revoke the old state
6458                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6459
6460                 route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6461
6462                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6463                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6464                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6465                 check_added_monitors!(nodes[1], 1);
6466                 assert_eq!(events.len(), 2);
6467                 match events[0] {
6468                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6469                         _ => panic!("Unexpected event"),
6470                 }
6471                 match events[1] {
6472                         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, .. } } => {
6473                                 assert!(update_add_htlcs.is_empty());
6474                                 assert_eq!(update_fail_htlcs.len(), 1);
6475                                 assert!(update_fulfill_htlcs.is_empty());
6476                                 assert!(update_fail_malformed_htlcs.is_empty());
6477                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6478
6479                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6480                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6481
6482                                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6483                                 assert_eq!(events.len(), 1);
6484                                 match events[0] {
6485                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6486                                         _ => panic!("Unexpected event"),
6487                                 }
6488                                 let events = nodes[0].node.get_and_clear_pending_events();
6489                                 assert_eq!(events.len(), 1);
6490                                 match events[0] {
6491                                         Event::PaymentFailed { .. } => {},
6492                                         _ => panic!("Unexpected event"),
6493                                 }
6494                         },
6495                         _ => panic!("Unexpected event"),
6496                 }
6497         }
6498
6499         fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool) {
6500                 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
6501                 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
6502                 // commitment transaction anymore.
6503                 // To do this, we have the peer which will broadcast a revoked commitment transaction send
6504                 // a number of update_fail/commitment_signed updates without ever sending the RAA in
6505                 // response to our commitment_signed. This is somewhat misbehavior-y, though not
6506                 // technically disallowed and we should probably handle it reasonably.
6507                 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
6508                 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
6509                 // transactions:
6510                 // * Once we move it out of our holding cell/add it, we will immediately include it in a
6511                 //   commitment_signed (implying it will be in the latest remote commitment transaction).
6512                 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
6513                 //   and once they revoke the previous commitment transaction (allowing us to send a new
6514                 //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
6515                 let mut nodes = create_network(3);
6516
6517                 // Create some initial channels
6518                 create_announced_chan_between_nodes(&nodes, 0, 1);
6519                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6520
6521                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6522                 // Get the will-be-revoked local txn from nodes[2]
6523                 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6524                 // Revoke the old state
6525                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6526
6527                 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6528                 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6529                 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6530
6531                 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, PaymentFailReason::PreimageUnknown));
6532                 check_added_monitors!(nodes[2], 1);
6533                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6534                 assert!(updates.update_add_htlcs.is_empty());
6535                 assert!(updates.update_fulfill_htlcs.is_empty());
6536                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6537                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6538                 assert!(updates.update_fee.is_none());
6539                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6540                 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
6541                 // Drop the last RAA from 3 -> 2
6542
6543                 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, PaymentFailReason::PreimageUnknown));
6544                 check_added_monitors!(nodes[2], 1);
6545                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6546                 assert!(updates.update_add_htlcs.is_empty());
6547                 assert!(updates.update_fulfill_htlcs.is_empty());
6548                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6549                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6550                 assert!(updates.update_fee.is_none());
6551                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6552                 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6553                 check_added_monitors!(nodes[1], 1);
6554                 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
6555                 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6556                 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6557                 check_added_monitors!(nodes[2], 1);
6558
6559                 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, PaymentFailReason::PreimageUnknown));
6560                 check_added_monitors!(nodes[2], 1);
6561                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6562                 assert!(updates.update_add_htlcs.is_empty());
6563                 assert!(updates.update_fulfill_htlcs.is_empty());
6564                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6565                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6566                 assert!(updates.update_fee.is_none());
6567                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6568                 // At this point first_payment_hash has dropped out of the latest two commitment
6569                 // transactions that nodes[1] is tracking...
6570                 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6571                 check_added_monitors!(nodes[1], 1);
6572                 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
6573                 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6574                 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6575                 check_added_monitors!(nodes[2], 1);
6576
6577                 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
6578                 // on nodes[2]'s RAA.
6579                 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
6580                 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6581                 nodes[1].node.send_payment(route, fourth_payment_hash).unwrap();
6582                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
6583                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6584                 check_added_monitors!(nodes[1], 0);
6585
6586                 if deliver_bs_raa {
6587                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa).unwrap();
6588                         // One monitor for the new revocation preimage, one as we generate a commitment for
6589                         // nodes[0] to fail first_payment_hash backwards.
6590                         check_added_monitors!(nodes[1], 2);
6591                 }
6592
6593                 let mut failed_htlcs = HashSet::new();
6594                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6595
6596                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6597                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6598
6599                 let events = nodes[1].node.get_and_clear_pending_events();
6600                 assert_eq!(events.len(), 1);
6601                 match events[0] {
6602                         Event::PaymentFailed { ref payment_hash, .. } => {
6603                                 assert_eq!(*payment_hash, fourth_payment_hash);
6604                         },
6605                         _ => panic!("Unexpected event"),
6606                 }
6607
6608                 if !deliver_bs_raa {
6609                         // If we delivered the RAA already then we already failed first_payment_hash backwards.
6610                         check_added_monitors!(nodes[1], 1);
6611                 }
6612
6613                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6614                 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
6615                 match events[if deliver_bs_raa { 2 } else { 0 }] {
6616                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6617                         _ => panic!("Unexpected event"),
6618                 }
6619                 if deliver_bs_raa {
6620                         match events[0] {
6621                                 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, .. } } => {
6622                                         assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
6623                                         assert_eq!(update_add_htlcs.len(), 1);
6624                                         assert!(update_fulfill_htlcs.is_empty());
6625                                         assert!(update_fail_htlcs.is_empty());
6626                                         assert!(update_fail_malformed_htlcs.is_empty());
6627                                 },
6628                                 _ => panic!("Unexpected event"),
6629                         }
6630                 }
6631                 // Due to the way backwards-failing occurs we do the updates in two steps.
6632                 let updates = match events[1] {
6633                         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, .. } } => {
6634                                 assert!(update_add_htlcs.is_empty());
6635                                 assert_eq!(update_fail_htlcs.len(), 1);
6636                                 assert!(update_fulfill_htlcs.is_empty());
6637                                 assert!(update_fail_malformed_htlcs.is_empty());
6638                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6639
6640                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6641                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
6642                                 check_added_monitors!(nodes[0], 1);
6643                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6644                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6645                                 check_added_monitors!(nodes[1], 1);
6646                                 let bs_second_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6647                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
6648                                 check_added_monitors!(nodes[1], 1);
6649                                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6650                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6651                                 check_added_monitors!(nodes[0], 1);
6652
6653                                 if !deliver_bs_raa {
6654                                         // If we delievered B's RAA we got an unknown preimage error, not something
6655                                         // that we should update our routing table for.
6656                                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6657                                         assert_eq!(events.len(), 1);
6658                                         match events[0] {
6659                                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6660                                                 _ => panic!("Unexpected event"),
6661                                         }
6662                                 }
6663                                 let events = nodes[0].node.get_and_clear_pending_events();
6664                                 assert_eq!(events.len(), 1);
6665                                 match events[0] {
6666                                         Event::PaymentFailed { ref payment_hash, .. } => {
6667                                                 assert!(failed_htlcs.insert(payment_hash.0));
6668                                         },
6669                                         _ => panic!("Unexpected event"),
6670                                 }
6671
6672                                 bs_second_update
6673                         },
6674                         _ => panic!("Unexpected event"),
6675                 };
6676
6677                 assert!(updates.update_add_htlcs.is_empty());
6678                 assert_eq!(updates.update_fail_htlcs.len(), 2);
6679                 assert!(updates.update_fulfill_htlcs.is_empty());
6680                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6681                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6682                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[1]).unwrap();
6683                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6684
6685                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6686                 assert_eq!(events.len(), 2);
6687                 for event in events {
6688                         match event {
6689                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6690                                 _ => panic!("Unexpected event"),
6691                         }
6692                 }
6693
6694                 let events = nodes[0].node.get_and_clear_pending_events();
6695                 assert_eq!(events.len(), 2);
6696                 match events[0] {
6697                         Event::PaymentFailed { ref payment_hash, .. } => {
6698                                 assert!(failed_htlcs.insert(payment_hash.0));
6699                         },
6700                         _ => panic!("Unexpected event"),
6701                 }
6702                 match events[1] {
6703                         Event::PaymentFailed { ref payment_hash, .. } => {
6704                                 assert!(failed_htlcs.insert(payment_hash.0));
6705                         },
6706                         _ => panic!("Unexpected event"),
6707                 }
6708
6709                 assert!(failed_htlcs.contains(&first_payment_hash.0));
6710                 assert!(failed_htlcs.contains(&second_payment_hash.0));
6711                 assert!(failed_htlcs.contains(&third_payment_hash.0));
6712         }
6713
6714         #[test]
6715         fn test_commitment_revoked_fail_backward_exhaustive() {
6716                 do_test_commitment_revoked_fail_backward_exhaustive(false);
6717                 do_test_commitment_revoked_fail_backward_exhaustive(true);
6718         }
6719
6720         #[test]
6721         fn test_htlc_ignore_latest_remote_commitment() {
6722                 // Test that HTLC transactions spending the latest remote commitment transaction are simply
6723                 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
6724                 let nodes = create_network(2);
6725                 create_announced_chan_between_nodes(&nodes, 0, 1);
6726
6727                 route_payment(&nodes[0], &[&nodes[1]], 10000000);
6728                 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
6729                 {
6730                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6731                         assert_eq!(events.len(), 1);
6732                         match events[0] {
6733                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6734                                         assert_eq!(flags & 0b10, 0b10);
6735                                 },
6736                                 _ => panic!("Unexpected event"),
6737                         }
6738                 }
6739
6740                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6741                 assert_eq!(node_txn.len(), 2);
6742
6743                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6744                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6745
6746                 {
6747                         let events = nodes[1].node.get_and_clear_pending_msg_events();
6748                         assert_eq!(events.len(), 1);
6749                         match events[0] {
6750                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6751                                         assert_eq!(flags & 0b10, 0b10);
6752                                 },
6753                                 _ => panic!("Unexpected event"),
6754                         }
6755                 }
6756
6757                 // Duplicate the block_connected call since this may happen due to other listeners
6758                 // registering new transactions
6759                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6760         }
6761
6762         #[test]
6763         fn test_force_close_fail_back() {
6764                 // Check which HTLCs are failed-backwards on channel force-closure
6765                 let mut nodes = create_network(3);
6766                 create_announced_chan_between_nodes(&nodes, 0, 1);
6767                 create_announced_chan_between_nodes(&nodes, 1, 2);
6768
6769                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
6770
6771                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6772
6773                 let mut payment_event = {
6774                         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6775                         check_added_monitors!(nodes[0], 1);
6776
6777                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6778                         assert_eq!(events.len(), 1);
6779                         SendEvent::from_event(events.remove(0))
6780                 };
6781
6782                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6783                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6784
6785                 let events_1 = nodes[1].node.get_and_clear_pending_events();
6786                 assert_eq!(events_1.len(), 1);
6787                 match events_1[0] {
6788                         Event::PendingHTLCsForwardable { .. } => { },
6789                         _ => panic!("Unexpected event"),
6790                 };
6791
6792                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
6793                 nodes[1].node.process_pending_htlc_forwards();
6794
6795                 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6796                 assert_eq!(events_2.len(), 1);
6797                 payment_event = SendEvent::from_event(events_2.remove(0));
6798                 assert_eq!(payment_event.msgs.len(), 1);
6799
6800                 check_added_monitors!(nodes[1], 1);
6801                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6802                 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
6803                 check_added_monitors!(nodes[2], 1);
6804                 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6805
6806                 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
6807                 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
6808                 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
6809
6810                 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
6811                 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6812                 assert_eq!(events_3.len(), 1);
6813                 match events_3[0] {
6814                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6815                                 assert_eq!(flags & 0b10, 0b10);
6816                         },
6817                         _ => panic!("Unexpected event"),
6818                 }
6819
6820                 let tx = {
6821                         let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6822                         // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
6823                         // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
6824                         // back to nodes[1] upon timeout otherwise.
6825                         assert_eq!(node_txn.len(), 1);
6826                         node_txn.remove(0)
6827                 };
6828
6829                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6830                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6831
6832                 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6833                 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
6834                 assert_eq!(events_4.len(), 1);
6835                 match events_4[0] {
6836                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6837                                 assert_eq!(flags & 0b10, 0b10);
6838                         },
6839                         _ => panic!("Unexpected event"),
6840                 }
6841
6842                 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
6843                 {
6844                         let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
6845                         monitors.get_mut(&OutPoint::new(Sha256dHash::from(&payment_event.commitment_msg.channel_id[..]), 0)).unwrap()
6846                                 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
6847                 }
6848                 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6849                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6850                 assert_eq!(node_txn.len(), 1);
6851                 assert_eq!(node_txn[0].input.len(), 1);
6852                 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
6853                 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
6854                 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
6855
6856                 check_spends!(node_txn[0], tx);
6857         }
6858
6859         #[test]
6860         fn test_unconf_chan() {
6861                 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
6862                 let nodes = create_network(2);
6863                 create_announced_chan_between_nodes(&nodes, 0, 1);
6864
6865                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6866                 assert_eq!(channel_state.by_id.len(), 1);
6867                 assert_eq!(channel_state.short_to_id.len(), 1);
6868                 mem::drop(channel_state);
6869
6870                 let mut headers = Vec::new();
6871                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6872                 headers.push(header.clone());
6873                 for _i in 2..100 {
6874                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6875                         headers.push(header.clone());
6876                 }
6877                 while !headers.is_empty() {
6878                         nodes[0].node.block_disconnected(&headers.pop().unwrap());
6879                 }
6880                 {
6881                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6882                         assert_eq!(events.len(), 1);
6883                         match events[0] {
6884                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6885                                         assert_eq!(flags & 0b10, 0b10);
6886                                 },
6887                                 _ => panic!("Unexpected event"),
6888                         }
6889                 }
6890                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6891                 assert_eq!(channel_state.by_id.len(), 0);
6892                 assert_eq!(channel_state.short_to_id.len(), 0);
6893         }
6894
6895         macro_rules! get_chan_reestablish_msgs {
6896                 ($src_node: expr, $dst_node: expr) => {
6897                         {
6898                                 let mut res = Vec::with_capacity(1);
6899                                 for msg in $src_node.node.get_and_clear_pending_msg_events() {
6900                                         if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
6901                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6902                                                 res.push(msg.clone());
6903                                         } else {
6904                                                 panic!("Unexpected event")
6905                                         }
6906                                 }
6907                                 res
6908                         }
6909                 }
6910         }
6911
6912         macro_rules! handle_chan_reestablish_msgs {
6913                 ($src_node: expr, $dst_node: expr) => {
6914                         {
6915                                 let msg_events = $src_node.node.get_and_clear_pending_msg_events();
6916                                 let mut idx = 0;
6917                                 let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
6918                                         idx += 1;
6919                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6920                                         Some(msg.clone())
6921                                 } else {
6922                                         None
6923                                 };
6924
6925                                 let mut revoke_and_ack = None;
6926                                 let mut commitment_update = None;
6927                                 let order = if let Some(ev) = msg_events.get(idx) {
6928                                         idx += 1;
6929                                         match ev {
6930                                                 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6931                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6932                                                         revoke_and_ack = Some(msg.clone());
6933                                                         RAACommitmentOrder::RevokeAndACKFirst
6934                                                 },
6935                                                 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6936                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6937                                                         commitment_update = Some(updates.clone());
6938                                                         RAACommitmentOrder::CommitmentFirst
6939                                                 },
6940                                                 _ => panic!("Unexpected event"),
6941                                         }
6942                                 } else {
6943                                         RAACommitmentOrder::CommitmentFirst
6944                                 };
6945
6946                                 if let Some(ev) = msg_events.get(idx) {
6947                                         match ev {
6948                                                 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6949                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6950                                                         assert!(revoke_and_ack.is_none());
6951                                                         revoke_and_ack = Some(msg.clone());
6952                                                 },
6953                                                 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6954                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6955                                                         assert!(commitment_update.is_none());
6956                                                         commitment_update = Some(updates.clone());
6957                                                 },
6958                                                 _ => panic!("Unexpected event"),
6959                                         }
6960                                 }
6961
6962                                 (funding_locked, revoke_and_ack, commitment_update, order)
6963                         }
6964                 }
6965         }
6966
6967         /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
6968         /// for claims/fails they are separated out.
6969         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)) {
6970                 node_a.node.peer_connected(&node_b.node.get_our_node_id());
6971                 let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
6972                 node_b.node.peer_connected(&node_a.node.get_our_node_id());
6973                 let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
6974
6975                 if send_funding_locked.0 {
6976                         // If a expects a funding_locked, it better not think it has received a revoke_and_ack
6977                         // from b
6978                         for reestablish in reestablish_1.iter() {
6979                                 assert_eq!(reestablish.next_remote_commitment_number, 0);
6980                         }
6981                 }
6982                 if send_funding_locked.1 {
6983                         // If b expects a funding_locked, it better not think it has received a revoke_and_ack
6984                         // from a
6985                         for reestablish in reestablish_2.iter() {
6986                                 assert_eq!(reestablish.next_remote_commitment_number, 0);
6987                         }
6988                 }
6989                 if send_funding_locked.0 || send_funding_locked.1 {
6990                         // If we expect any funding_locked's, both sides better have set
6991                         // next_local_commitment_number to 1
6992                         for reestablish in reestablish_1.iter() {
6993                                 assert_eq!(reestablish.next_local_commitment_number, 1);
6994                         }
6995                         for reestablish in reestablish_2.iter() {
6996                                 assert_eq!(reestablish.next_local_commitment_number, 1);
6997                         }
6998                 }
6999
7000                 let mut resp_1 = Vec::new();
7001                 for msg in reestablish_1 {
7002                         node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg).unwrap();
7003                         resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
7004                 }
7005                 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
7006                         check_added_monitors!(node_b, 1);
7007                 } else {
7008                         check_added_monitors!(node_b, 0);
7009                 }
7010
7011                 let mut resp_2 = Vec::new();
7012                 for msg in reestablish_2 {
7013                         node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg).unwrap();
7014                         resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
7015                 }
7016                 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
7017                         check_added_monitors!(node_a, 1);
7018                 } else {
7019                         check_added_monitors!(node_a, 0);
7020                 }
7021
7022                 // We dont yet support both needing updates, as that would require a different commitment dance:
7023                 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
7024                         (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
7025
7026                 for chan_msgs in resp_1.drain(..) {
7027                         if send_funding_locked.0 {
7028                                 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
7029                                 let announcement_event = node_a.node.get_and_clear_pending_msg_events();
7030                                 if !announcement_event.is_empty() {
7031                                         assert_eq!(announcement_event.len(), 1);
7032                                         if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
7033                                                 //TODO: Test announcement_sigs re-sending
7034                                         } else { panic!("Unexpected event!"); }
7035                                 }
7036                         } else {
7037                                 assert!(chan_msgs.0.is_none());
7038                         }
7039                         if pending_raa.0 {
7040                                 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
7041                                 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
7042                                 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
7043                                 check_added_monitors!(node_a, 1);
7044                         } else {
7045                                 assert!(chan_msgs.1.is_none());
7046                         }
7047                         if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
7048                                 let commitment_update = chan_msgs.2.unwrap();
7049                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
7050                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
7051                                 } else {
7052                                         assert!(commitment_update.update_add_htlcs.is_empty());
7053                                 }
7054                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
7055                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
7056                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
7057                                 for update_add in commitment_update.update_add_htlcs {
7058                                         node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add).unwrap();
7059                                 }
7060                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
7061                                         node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill).unwrap();
7062                                 }
7063                                 for update_fail in commitment_update.update_fail_htlcs {
7064                                         node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail).unwrap();
7065                                 }
7066
7067                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
7068                                         commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
7069                                 } else {
7070                                         node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
7071                                         check_added_monitors!(node_a, 1);
7072                                         let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
7073                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
7074                                         node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7075                                         assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
7076                                         check_added_monitors!(node_b, 1);
7077                                 }
7078                         } else {
7079                                 assert!(chan_msgs.2.is_none());
7080                         }
7081                 }
7082
7083                 for chan_msgs in resp_2.drain(..) {
7084                         if send_funding_locked.1 {
7085                                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
7086                                 let announcement_event = node_b.node.get_and_clear_pending_msg_events();
7087                                 if !announcement_event.is_empty() {
7088                                         assert_eq!(announcement_event.len(), 1);
7089                                         if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
7090                                                 //TODO: Test announcement_sigs re-sending
7091                                         } else { panic!("Unexpected event!"); }
7092                                 }
7093                         } else {
7094                                 assert!(chan_msgs.0.is_none());
7095                         }
7096                         if pending_raa.1 {
7097                                 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
7098                                 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
7099                                 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
7100                                 check_added_monitors!(node_b, 1);
7101                         } else {
7102                                 assert!(chan_msgs.1.is_none());
7103                         }
7104                         if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
7105                                 let commitment_update = chan_msgs.2.unwrap();
7106                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
7107                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
7108                                 }
7109                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
7110                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
7111                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
7112                                 for update_add in commitment_update.update_add_htlcs {
7113                                         node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add).unwrap();
7114                                 }
7115                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
7116                                         node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill).unwrap();
7117                                 }
7118                                 for update_fail in commitment_update.update_fail_htlcs {
7119                                         node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail).unwrap();
7120                                 }
7121
7122                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
7123                                         commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
7124                                 } else {
7125                                         node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
7126                                         check_added_monitors!(node_b, 1);
7127                                         let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
7128                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
7129                                         node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7130                                         assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
7131                                         check_added_monitors!(node_a, 1);
7132                                 }
7133                         } else {
7134                                 assert!(chan_msgs.2.is_none());
7135                         }
7136                 }
7137         }
7138
7139         #[test]
7140         fn test_simple_peer_disconnect() {
7141                 // Test that we can reconnect when there are no lost messages
7142                 let nodes = create_network(3);
7143                 create_announced_chan_between_nodes(&nodes, 0, 1);
7144                 create_announced_chan_between_nodes(&nodes, 1, 2);
7145
7146                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7147                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7148                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7149
7150                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7151                 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7152                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
7153                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
7154
7155                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7156                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7157                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7158
7159                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7160                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7161                 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7162                 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7163
7164                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7165                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7166
7167                 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3);
7168                 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
7169
7170                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
7171                 {
7172                         let events = nodes[0].node.get_and_clear_pending_events();
7173                         assert_eq!(events.len(), 2);
7174                         match events[0] {
7175                                 Event::PaymentSent { payment_preimage } => {
7176                                         assert_eq!(payment_preimage, payment_preimage_3);
7177                                 },
7178                                 _ => panic!("Unexpected event"),
7179                         }
7180                         match events[1] {
7181                                 Event::PaymentFailed { payment_hash, rejected_by_dest } => {
7182                                         assert_eq!(payment_hash, payment_hash_5);
7183                                         assert!(rejected_by_dest);
7184                                 },
7185                                 _ => panic!("Unexpected event"),
7186                         }
7187                 }
7188
7189                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
7190                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
7191         }
7192
7193         fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
7194                 // Test that we can reconnect when in-flight HTLC updates get dropped
7195                 let mut nodes = create_network(2);
7196                 if messages_delivered == 0 {
7197                         create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
7198                         // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
7199                 } else {
7200                         create_announced_chan_between_nodes(&nodes, 0, 1);
7201                 }
7202
7203                 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();
7204                 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7205
7206                 let payment_event = {
7207                         nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
7208                         check_added_monitors!(nodes[0], 1);
7209
7210                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7211                         assert_eq!(events.len(), 1);
7212                         SendEvent::from_event(events.remove(0))
7213                 };
7214                 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
7215
7216                 if messages_delivered < 2 {
7217                         // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
7218                 } else {
7219                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7220                         if messages_delivered >= 3 {
7221                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7222                                 check_added_monitors!(nodes[1], 1);
7223                                 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7224
7225                                 if messages_delivered >= 4 {
7226                                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7227                                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7228                                         check_added_monitors!(nodes[0], 1);
7229
7230                                         if messages_delivered >= 5 {
7231                                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
7232                                                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7233                                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7234                                                 check_added_monitors!(nodes[0], 1);
7235
7236                                                 if messages_delivered >= 6 {
7237                                                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7238                                                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7239                                                         check_added_monitors!(nodes[1], 1);
7240                                                 }
7241                                         }
7242                                 }
7243                         }
7244                 }
7245
7246                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7247                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7248                 if messages_delivered < 3 {
7249                         // Even if the funding_locked messages get exchanged, as long as nothing further was
7250                         // received on either side, both sides will need to resend them.
7251                         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
7252                 } else if messages_delivered == 3 {
7253                         // nodes[0] still wants its RAA + commitment_signed
7254                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
7255                 } else if messages_delivered == 4 {
7256                         // nodes[0] still wants its commitment_signed
7257                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
7258                 } else if messages_delivered == 5 {
7259                         // nodes[1] still wants its final RAA
7260                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
7261                 } else if messages_delivered == 6 {
7262                         // Everything was delivered...
7263                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7264                 }
7265
7266                 let events_1 = nodes[1].node.get_and_clear_pending_events();
7267                 assert_eq!(events_1.len(), 1);
7268                 match events_1[0] {
7269                         Event::PendingHTLCsForwardable { .. } => { },
7270                         _ => panic!("Unexpected event"),
7271                 };
7272
7273                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7274                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7275                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7276
7277                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7278                 nodes[1].node.process_pending_htlc_forwards();
7279
7280                 let events_2 = nodes[1].node.get_and_clear_pending_events();
7281                 assert_eq!(events_2.len(), 1);
7282                 match events_2[0] {
7283                         Event::PaymentReceived { ref payment_hash, amt } => {
7284                                 assert_eq!(payment_hash_1, *payment_hash);
7285                                 assert_eq!(amt, 1000000);
7286                         },
7287                         _ => panic!("Unexpected event"),
7288                 }
7289
7290                 nodes[1].node.claim_funds(payment_preimage_1);
7291                 check_added_monitors!(nodes[1], 1);
7292
7293                 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
7294                 assert_eq!(events_3.len(), 1);
7295                 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
7296                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
7297                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7298                                 assert!(updates.update_add_htlcs.is_empty());
7299                                 assert!(updates.update_fail_htlcs.is_empty());
7300                                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
7301                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
7302                                 assert!(updates.update_fee.is_none());
7303                                 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
7304                         },
7305                         _ => panic!("Unexpected event"),
7306                 };
7307
7308                 if messages_delivered >= 1 {
7309                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc).unwrap();
7310
7311                         let events_4 = nodes[0].node.get_and_clear_pending_events();
7312                         assert_eq!(events_4.len(), 1);
7313                         match events_4[0] {
7314                                 Event::PaymentSent { ref payment_preimage } => {
7315                                         assert_eq!(payment_preimage_1, *payment_preimage);
7316                                 },
7317                                 _ => panic!("Unexpected event"),
7318                         }
7319
7320                         if messages_delivered >= 2 {
7321                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
7322                                 check_added_monitors!(nodes[0], 1);
7323                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7324
7325                                 if messages_delivered >= 3 {
7326                                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7327                                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7328                                         check_added_monitors!(nodes[1], 1);
7329
7330                                         if messages_delivered >= 4 {
7331                                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
7332                                                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7333                                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7334                                                 check_added_monitors!(nodes[1], 1);
7335
7336                                                 if messages_delivered >= 5 {
7337                                                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7338                                                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7339                                                         check_added_monitors!(nodes[0], 1);
7340                                                 }
7341                                         }
7342                                 }
7343                         }
7344                 }
7345
7346                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7347                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7348                 if messages_delivered < 2 {
7349                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
7350                         //TODO: Deduplicate PaymentSent events, then enable this if:
7351                         //if messages_delivered < 1 {
7352                                 let events_4 = nodes[0].node.get_and_clear_pending_events();
7353                                 assert_eq!(events_4.len(), 1);
7354                                 match events_4[0] {
7355                                         Event::PaymentSent { ref payment_preimage } => {
7356                                                 assert_eq!(payment_preimage_1, *payment_preimage);
7357                                         },
7358                                         _ => panic!("Unexpected event"),
7359                                 }
7360                         //}
7361                 } else if messages_delivered == 2 {
7362                         // nodes[0] still wants its RAA + commitment_signed
7363                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
7364                 } else if messages_delivered == 3 {
7365                         // nodes[0] still wants its commitment_signed
7366                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
7367                 } else if messages_delivered == 4 {
7368                         // nodes[1] still wants its final RAA
7369                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
7370                 } else if messages_delivered == 5 {
7371                         // Everything was delivered...
7372                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7373                 }
7374
7375                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7376                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7377                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7378
7379                 // Channel should still work fine...
7380                 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
7381                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7382         }
7383
7384         #[test]
7385         fn test_drop_messages_peer_disconnect_a() {
7386                 do_test_drop_messages_peer_disconnect(0);
7387                 do_test_drop_messages_peer_disconnect(1);
7388                 do_test_drop_messages_peer_disconnect(2);
7389                 do_test_drop_messages_peer_disconnect(3);
7390         }
7391
7392         #[test]
7393         fn test_drop_messages_peer_disconnect_b() {
7394                 do_test_drop_messages_peer_disconnect(4);
7395                 do_test_drop_messages_peer_disconnect(5);
7396                 do_test_drop_messages_peer_disconnect(6);
7397         }
7398
7399         #[test]
7400         fn test_funding_peer_disconnect() {
7401                 // Test that we can lock in our funding tx while disconnected
7402                 let nodes = create_network(2);
7403                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
7404
7405                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7406                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7407
7408                 confirm_transaction(&nodes[0].chain_monitor, &tx, tx.version);
7409                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7410                 assert_eq!(events_1.len(), 1);
7411                 match events_1[0] {
7412                         MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7413                                 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7414                         },
7415                         _ => panic!("Unexpected event"),
7416                 }
7417
7418                 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7419
7420                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7421                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7422
7423                 confirm_transaction(&nodes[1].chain_monitor, &tx, tx.version);
7424                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7425                 assert_eq!(events_2.len(), 2);
7426                 match events_2[0] {
7427                         MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7428                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7429                         },
7430                         _ => panic!("Unexpected event"),
7431                 }
7432                 match events_2[1] {
7433                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ } => {
7434                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7435                         },
7436                         _ => panic!("Unexpected event"),
7437                 }
7438
7439                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7440
7441                 // TODO: We shouldn't need to manually pass list_usable_chanels here once we support
7442                 // rebroadcasting announcement_signatures upon reconnect.
7443
7444                 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();
7445                 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
7446                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
7447         }
7448
7449         #[test]
7450         fn test_drop_messages_peer_disconnect_dual_htlc() {
7451                 // Test that we can handle reconnecting when both sides of a channel have pending
7452                 // commitment_updates when we disconnect.
7453                 let mut nodes = create_network(2);
7454                 create_announced_chan_between_nodes(&nodes, 0, 1);
7455
7456                 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7457
7458                 // Now try to send a second payment which will fail to send
7459                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7460                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7461
7462                 nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
7463                 check_added_monitors!(nodes[0], 1);
7464
7465                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7466                 assert_eq!(events_1.len(), 1);
7467                 match events_1[0] {
7468                         MessageSendEvent::UpdateHTLCs { .. } => {},
7469                         _ => panic!("Unexpected event"),
7470                 }
7471
7472                 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7473                 check_added_monitors!(nodes[1], 1);
7474
7475                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7476                 assert_eq!(events_2.len(), 1);
7477                 match events_2[0] {
7478                         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 } } => {
7479                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7480                                 assert!(update_add_htlcs.is_empty());
7481                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7482                                 assert!(update_fail_htlcs.is_empty());
7483                                 assert!(update_fail_malformed_htlcs.is_empty());
7484                                 assert!(update_fee.is_none());
7485
7486                                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7487                                 let events_3 = nodes[0].node.get_and_clear_pending_events();
7488                                 assert_eq!(events_3.len(), 1);
7489                                 match events_3[0] {
7490                                         Event::PaymentSent { ref payment_preimage } => {
7491                                                 assert_eq!(*payment_preimage, payment_preimage_1);
7492                                         },
7493                                         _ => panic!("Unexpected event"),
7494                                 }
7495
7496                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
7497                                 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7498                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7499                                 check_added_monitors!(nodes[0], 1);
7500                         },
7501                         _ => panic!("Unexpected event"),
7502                 }
7503
7504                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7505                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7506
7507                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7508                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7509                 assert_eq!(reestablish_1.len(), 1);
7510                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7511                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7512                 assert_eq!(reestablish_2.len(), 1);
7513
7514                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7515                 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7516                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7517                 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7518
7519                 assert!(as_resp.0.is_none());
7520                 assert!(bs_resp.0.is_none());
7521
7522                 assert!(bs_resp.1.is_none());
7523                 assert!(bs_resp.2.is_none());
7524
7525                 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7526
7527                 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
7528                 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
7529                 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7530                 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7531                 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
7532                 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();
7533                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7534                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7535                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7536                 check_added_monitors!(nodes[1], 1);
7537
7538                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap();
7539                 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7540                 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
7541                 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
7542                 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
7543                 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
7544                 assert!(bs_second_commitment_signed.update_fee.is_none());
7545                 check_added_monitors!(nodes[1], 1);
7546
7547                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7548                 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7549                 assert!(as_commitment_signed.update_add_htlcs.is_empty());
7550                 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
7551                 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
7552                 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
7553                 assert!(as_commitment_signed.update_fee.is_none());
7554                 check_added_monitors!(nodes[0], 1);
7555
7556                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
7557                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7558                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7559                 check_added_monitors!(nodes[0], 1);
7560
7561                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
7562                 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7563                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7564                 check_added_monitors!(nodes[1], 1);
7565
7566                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7567                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7568                 check_added_monitors!(nodes[1], 1);
7569
7570                 let events_4 = nodes[1].node.get_and_clear_pending_events();
7571                 assert_eq!(events_4.len(), 1);
7572                 match events_4[0] {
7573                         Event::PendingHTLCsForwardable { .. } => { },
7574                         _ => panic!("Unexpected event"),
7575                 };
7576
7577                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7578                 nodes[1].node.process_pending_htlc_forwards();
7579
7580                 let events_5 = nodes[1].node.get_and_clear_pending_events();
7581                 assert_eq!(events_5.len(), 1);
7582                 match events_5[0] {
7583                         Event::PaymentReceived { ref payment_hash, amt: _ } => {
7584                                 assert_eq!(payment_hash_2, *payment_hash);
7585                         },
7586                         _ => panic!("Unexpected event"),
7587                 }
7588
7589                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
7590                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7591                 check_added_monitors!(nodes[0], 1);
7592
7593                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7594         }
7595
7596         #[test]
7597         fn test_simple_monitor_permanent_update_fail() {
7598                 // Test that we handle a simple permanent monitor update failure
7599                 let mut nodes = create_network(2);
7600                 create_announced_chan_between_nodes(&nodes, 0, 1);
7601
7602                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7603                 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7604
7605                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7606                 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route, payment_hash_1) {} else { panic!(); }
7607                 check_added_monitors!(nodes[0], 1);
7608
7609                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7610                 assert_eq!(events_1.len(), 2);
7611                 match events_1[0] {
7612                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7613                         _ => panic!("Unexpected event"),
7614                 };
7615                 match events_1[1] {
7616                         MessageSendEvent::HandleError { node_id, .. } => assert_eq!(node_id, nodes[1].node.get_our_node_id()),
7617                         _ => panic!("Unexpected event"),
7618                 };
7619
7620                 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7621                 // PaymentFailed event
7622
7623                 assert_eq!(nodes[0].node.list_channels().len(), 0);
7624         }
7625
7626         fn do_test_simple_monitor_temporary_update_fail(disconnect: bool) {
7627                 // Test that we can recover from a simple temporary monitor update failure optionally with
7628                 // a disconnect in between
7629                 let mut nodes = create_network(2);
7630                 create_announced_chan_between_nodes(&nodes, 0, 1);
7631
7632                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7633                 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7634
7635                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7636                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_1) {} else { panic!(); }
7637                 check_added_monitors!(nodes[0], 1);
7638
7639                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7640                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7641                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7642
7643                 if disconnect {
7644                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7645                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7646                         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7647                 }
7648
7649                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7650                 nodes[0].node.test_restore_channel_monitor();
7651                 check_added_monitors!(nodes[0], 1);
7652
7653                 let mut events_2 = nodes[0].node.get_and_clear_pending_msg_events();
7654                 assert_eq!(events_2.len(), 1);
7655                 let payment_event = SendEvent::from_event(events_2.pop().unwrap());
7656                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7657                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7658                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7659
7660                 expect_pending_htlcs_forwardable!(nodes[1]);
7661
7662                 let events_3 = nodes[1].node.get_and_clear_pending_events();
7663                 assert_eq!(events_3.len(), 1);
7664                 match events_3[0] {
7665                         Event::PaymentReceived { ref payment_hash, amt } => {
7666                                 assert_eq!(payment_hash_1, *payment_hash);
7667                                 assert_eq!(amt, 1000000);
7668                         },
7669                         _ => panic!("Unexpected event"),
7670                 }
7671
7672                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_1);
7673
7674                 // Now set it to failed again...
7675                 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7676                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7677                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route, payment_hash_2) {} else { panic!(); }
7678                 check_added_monitors!(nodes[0], 1);
7679
7680                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7681                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7682                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7683
7684                 if disconnect {
7685                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7686                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7687                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7688                 }
7689
7690                 // ...and make sure we can force-close a TemporaryFailure channel with a PermanentFailure
7691                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7692                 nodes[0].node.test_restore_channel_monitor();
7693                 check_added_monitors!(nodes[0], 1);
7694
7695                 let events_5 = nodes[0].node.get_and_clear_pending_msg_events();
7696                 assert_eq!(events_5.len(), 1);
7697                 match events_5[0] {
7698                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7699                         _ => panic!("Unexpected event"),
7700                 }
7701
7702                 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7703                 // PaymentFailed event
7704
7705                 assert_eq!(nodes[0].node.list_channels().len(), 0);
7706         }
7707
7708         #[test]
7709         fn test_simple_monitor_temporary_update_fail() {
7710                 do_test_simple_monitor_temporary_update_fail(false);
7711                 do_test_simple_monitor_temporary_update_fail(true);
7712         }
7713
7714         fn do_test_monitor_temporary_update_fail(disconnect_count: usize) {
7715                 let disconnect_flags = 8 | 16;
7716
7717                 // Test that we can recover from a temporary monitor update failure with some in-flight
7718                 // HTLCs going on at the same time potentially with some disconnection thrown in.
7719                 // * First we route a payment, then get a temporary monitor update failure when trying to
7720                 //   route a second payment. We then claim the first payment.
7721                 // * If disconnect_count is set, we will disconnect at this point (which is likely as
7722                 //   TemporaryFailure likely indicates net disconnect which resulted in failing to update
7723                 //   the ChannelMonitor on a watchtower).
7724                 // * If !(disconnect_count & 16) we deliver a update_fulfill_htlc/CS for the first payment
7725                 //   immediately, otherwise we wait sconnect and deliver them via the reconnect
7726                 //   channel_reestablish processing (ie disconnect_count & 16 makes no sense if
7727                 //   disconnect_count & !disconnect_flags is 0).
7728                 // * We then update the channel monitor, reconnecting if disconnect_count is set and walk
7729                 //   through message sending, potentially disconnect/reconnecting multiple times based on
7730                 //   disconnect_count, to get the update_fulfill_htlc through.
7731                 // * We then walk through more message exchanges to get the original update_add_htlc
7732                 //   through, swapping message ordering based on disconnect_count & 8 and optionally
7733                 //   disconnect/reconnecting based on disconnect_count.
7734                 let mut nodes = create_network(2);
7735                 create_announced_chan_between_nodes(&nodes, 0, 1);
7736
7737                 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7738
7739                 // Now try to send a second payment which will fail to send
7740                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7741                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7742
7743                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7744                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_2) {} else { panic!(); }
7745                 check_added_monitors!(nodes[0], 1);
7746
7747                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7748                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7749                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7750
7751                 // Claim the previous payment, which will result in a update_fulfill_htlc/CS from nodes[1]
7752                 // but nodes[0] won't respond since it is frozen.
7753                 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7754                 check_added_monitors!(nodes[1], 1);
7755                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7756                 assert_eq!(events_2.len(), 1);
7757                 let (bs_initial_fulfill, bs_initial_commitment_signed) = match events_2[0] {
7758                         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 } } => {
7759                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7760                                 assert!(update_add_htlcs.is_empty());
7761                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7762                                 assert!(update_fail_htlcs.is_empty());
7763                                 assert!(update_fail_malformed_htlcs.is_empty());
7764                                 assert!(update_fee.is_none());
7765
7766                                 if (disconnect_count & 16) == 0 {
7767                                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7768                                         let events_3 = nodes[0].node.get_and_clear_pending_events();
7769                                         assert_eq!(events_3.len(), 1);
7770                                         match events_3[0] {
7771                                                 Event::PaymentSent { ref payment_preimage } => {
7772                                                         assert_eq!(*payment_preimage, payment_preimage_1);
7773                                                 },
7774                                                 _ => panic!("Unexpected event"),
7775                                         }
7776
7777                                         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) {
7778                                                 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
7779                                         } else { panic!(); }
7780                                 }
7781
7782                                 (update_fulfill_htlcs[0].clone(), commitment_signed.clone())
7783                         },
7784                         _ => panic!("Unexpected event"),
7785                 };
7786
7787                 if disconnect_count & !disconnect_flags > 0 {
7788                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7789                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7790                 }
7791
7792                 // Now fix monitor updating...
7793                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7794                 nodes[0].node.test_restore_channel_monitor();
7795                 check_added_monitors!(nodes[0], 1);
7796
7797                 macro_rules! disconnect_reconnect_peers { () => { {
7798                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7799                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7800
7801                         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7802                         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7803                         assert_eq!(reestablish_1.len(), 1);
7804                         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7805                         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7806                         assert_eq!(reestablish_2.len(), 1);
7807
7808                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7809                         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7810                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7811                         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7812
7813                         assert!(as_resp.0.is_none());
7814                         assert!(bs_resp.0.is_none());
7815
7816                         (reestablish_1, reestablish_2, as_resp, bs_resp)
7817                 } } }
7818
7819                 let (payment_event, initial_revoke_and_ack) = if disconnect_count & !disconnect_flags > 0 {
7820                         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7821                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7822
7823                         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7824                         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7825                         assert_eq!(reestablish_1.len(), 1);
7826                         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7827                         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7828                         assert_eq!(reestablish_2.len(), 1);
7829
7830                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7831                         check_added_monitors!(nodes[0], 0);
7832                         let mut as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7833                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7834                         check_added_monitors!(nodes[1], 0);
7835                         let mut bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7836
7837                         assert!(as_resp.0.is_none());
7838                         assert!(bs_resp.0.is_none());
7839
7840                         assert!(bs_resp.1.is_none());
7841                         if (disconnect_count & 16) == 0 {
7842                                 assert!(bs_resp.2.is_none());
7843
7844                                 assert!(as_resp.1.is_some());
7845                                 assert!(as_resp.2.is_some());
7846                                 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7847                         } else {
7848                                 assert!(bs_resp.2.as_ref().unwrap().update_add_htlcs.is_empty());
7849                                 assert!(bs_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7850                                 assert!(bs_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7851                                 assert!(bs_resp.2.as_ref().unwrap().update_fee.is_none());
7852                                 assert!(bs_resp.2.as_ref().unwrap().update_fulfill_htlcs == vec![bs_initial_fulfill]);
7853                                 assert!(bs_resp.2.as_ref().unwrap().commitment_signed == bs_initial_commitment_signed);
7854
7855                                 assert!(as_resp.1.is_none());
7856
7857                                 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();
7858                                 let events_3 = nodes[0].node.get_and_clear_pending_events();
7859                                 assert_eq!(events_3.len(), 1);
7860                                 match events_3[0] {
7861                                         Event::PaymentSent { ref payment_preimage } => {
7862                                                 assert_eq!(*payment_preimage, payment_preimage_1);
7863                                         },
7864                                         _ => panic!("Unexpected event"),
7865                                 }
7866
7867                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7868                                 let as_resp_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7869                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7870                                 check_added_monitors!(nodes[0], 1);
7871
7872                                 as_resp.1 = Some(as_resp_raa);
7873                                 bs_resp.2 = None;
7874                         }
7875
7876                         if disconnect_count & !disconnect_flags > 1 {
7877                                 let (second_reestablish_1, second_reestablish_2, second_as_resp, second_bs_resp) = disconnect_reconnect_peers!();
7878
7879                                 if (disconnect_count & 16) == 0 {
7880                                         assert!(reestablish_1 == second_reestablish_1);
7881                                         assert!(reestablish_2 == second_reestablish_2);
7882                                 }
7883                                 assert!(as_resp == second_as_resp);
7884                                 assert!(bs_resp == second_bs_resp);
7885                         }
7886
7887                         (SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), as_resp.2.unwrap()), as_resp.1.unwrap())
7888                 } else {
7889                         let mut events_4 = nodes[0].node.get_and_clear_pending_msg_events();
7890                         assert_eq!(events_4.len(), 2);
7891                         (SendEvent::from_event(events_4.remove(0)), match events_4[0] {
7892                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
7893                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7894                                         msg.clone()
7895                                 },
7896                                 _ => panic!("Unexpected event"),
7897                         })
7898                 };
7899
7900                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7901
7902                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7903                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7904                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7905                 // nodes[1] is awaiting an RAA from nodes[0] still so get_event_msg's assert(len == 1) passes
7906                 check_added_monitors!(nodes[1], 1);
7907
7908                 if disconnect_count & !disconnect_flags > 2 {
7909                         let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7910
7911                         assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7912                         assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7913
7914                         assert!(as_resp.2.is_none());
7915                         assert!(bs_resp.2.is_none());
7916                 }
7917
7918                 let as_commitment_update;
7919                 let bs_second_commitment_update;
7920
7921                 macro_rules! handle_bs_raa { () => {
7922                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7923                         as_commitment_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7924                         assert!(as_commitment_update.update_add_htlcs.is_empty());
7925                         assert!(as_commitment_update.update_fulfill_htlcs.is_empty());
7926                         assert!(as_commitment_update.update_fail_htlcs.is_empty());
7927                         assert!(as_commitment_update.update_fail_malformed_htlcs.is_empty());
7928                         assert!(as_commitment_update.update_fee.is_none());
7929                         check_added_monitors!(nodes[0], 1);
7930                 } }
7931
7932                 macro_rules! handle_initial_raa { () => {
7933                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &initial_revoke_and_ack).unwrap();
7934                         bs_second_commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7935                         assert!(bs_second_commitment_update.update_add_htlcs.is_empty());
7936                         assert!(bs_second_commitment_update.update_fulfill_htlcs.is_empty());
7937                         assert!(bs_second_commitment_update.update_fail_htlcs.is_empty());
7938                         assert!(bs_second_commitment_update.update_fail_malformed_htlcs.is_empty());
7939                         assert!(bs_second_commitment_update.update_fee.is_none());
7940                         check_added_monitors!(nodes[1], 1);
7941                 } }
7942
7943                 if (disconnect_count & 8) == 0 {
7944                         handle_bs_raa!();
7945
7946                         if disconnect_count & !disconnect_flags > 3 {
7947                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7948
7949                                 assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7950                                 assert!(bs_resp.1.is_none());
7951
7952                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7953                                 assert!(bs_resp.2.is_none());
7954
7955                                 assert!(as_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7956                         }
7957
7958                         handle_initial_raa!();
7959
7960                         if disconnect_count & !disconnect_flags > 4 {
7961                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7962
7963                                 assert!(as_resp.1.is_none());
7964                                 assert!(bs_resp.1.is_none());
7965
7966                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7967                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7968                         }
7969                 } else {
7970                         handle_initial_raa!();
7971
7972                         if disconnect_count & !disconnect_flags > 3 {
7973                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7974
7975                                 assert!(as_resp.1.is_none());
7976                                 assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7977
7978                                 assert!(as_resp.2.is_none());
7979                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7980
7981                                 assert!(bs_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7982                         }
7983
7984                         handle_bs_raa!();
7985
7986                         if disconnect_count & !disconnect_flags > 4 {
7987                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7988
7989                                 assert!(as_resp.1.is_none());
7990                                 assert!(bs_resp.1.is_none());
7991
7992                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7993                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7994                         }
7995                 }
7996
7997                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_update.commitment_signed).unwrap();
7998                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7999                 // No commitment_signed so get_event_msg's assert(len == 1) passes
8000                 check_added_monitors!(nodes[0], 1);
8001
8002                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_update.commitment_signed).unwrap();
8003                 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
8004                 // No commitment_signed so get_event_msg's assert(len == 1) passes
8005                 check_added_monitors!(nodes[1], 1);
8006
8007                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
8008                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8009                 check_added_monitors!(nodes[1], 1);
8010
8011                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
8012                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8013                 check_added_monitors!(nodes[0], 1);
8014
8015                 expect_pending_htlcs_forwardable!(nodes[1]);
8016
8017                 let events_5 = nodes[1].node.get_and_clear_pending_events();
8018                 assert_eq!(events_5.len(), 1);
8019                 match events_5[0] {
8020                         Event::PaymentReceived { ref payment_hash, amt } => {
8021                                 assert_eq!(payment_hash_2, *payment_hash);
8022                                 assert_eq!(amt, 1000000);
8023                         },
8024                         _ => panic!("Unexpected event"),
8025                 }
8026
8027                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
8028         }
8029
8030         #[test]
8031         fn test_monitor_temporary_update_fail_a() {
8032                 do_test_monitor_temporary_update_fail(0);
8033                 do_test_monitor_temporary_update_fail(1);
8034                 do_test_monitor_temporary_update_fail(2);
8035                 do_test_monitor_temporary_update_fail(3);
8036                 do_test_monitor_temporary_update_fail(4);
8037                 do_test_monitor_temporary_update_fail(5);
8038         }
8039
8040         #[test]
8041         fn test_monitor_temporary_update_fail_b() {
8042                 do_test_monitor_temporary_update_fail(2 | 8);
8043                 do_test_monitor_temporary_update_fail(3 | 8);
8044                 do_test_monitor_temporary_update_fail(4 | 8);
8045                 do_test_monitor_temporary_update_fail(5 | 8);
8046         }
8047
8048         #[test]
8049         fn test_monitor_temporary_update_fail_c() {
8050                 do_test_monitor_temporary_update_fail(1 | 16);
8051                 do_test_monitor_temporary_update_fail(2 | 16);
8052                 do_test_monitor_temporary_update_fail(3 | 16);
8053                 do_test_monitor_temporary_update_fail(2 | 8 | 16);
8054                 do_test_monitor_temporary_update_fail(3 | 8 | 16);
8055         }
8056
8057         #[test]
8058         fn test_monitor_update_fail_cs() {
8059                 // Tests handling of a monitor update failure when processing an incoming commitment_signed
8060                 let mut nodes = create_network(2);
8061                 create_announced_chan_between_nodes(&nodes, 0, 1);
8062
8063                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8064                 let (payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
8065                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
8066                 check_added_monitors!(nodes[0], 1);
8067
8068                 let send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8069                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8070
8071                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8072                 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() {
8073                         assert_eq!(err, "Failed to update ChannelMonitor");
8074                 } else { panic!(); }
8075                 check_added_monitors!(nodes[1], 1);
8076                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8077
8078                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8079                 nodes[1].node.test_restore_channel_monitor();
8080                 check_added_monitors!(nodes[1], 1);
8081                 let responses = nodes[1].node.get_and_clear_pending_msg_events();
8082                 assert_eq!(responses.len(), 2);
8083
8084                 match responses[0] {
8085                         MessageSendEvent::SendRevokeAndACK { ref msg, ref node_id } => {
8086                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8087                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &msg).unwrap();
8088                                 check_added_monitors!(nodes[0], 1);
8089                         },
8090                         _ => panic!("Unexpected event"),
8091                 }
8092                 match responses[1] {
8093                         MessageSendEvent::UpdateHTLCs { ref updates, ref node_id } => {
8094                                 assert!(updates.update_add_htlcs.is_empty());
8095                                 assert!(updates.update_fulfill_htlcs.is_empty());
8096                                 assert!(updates.update_fail_htlcs.is_empty());
8097                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8098                                 assert!(updates.update_fee.is_none());
8099                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8100
8101                                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8102                                 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() {
8103                                         assert_eq!(err, "Failed to update ChannelMonitor");
8104                                 } else { panic!(); }
8105                                 check_added_monitors!(nodes[0], 1);
8106                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8107                         },
8108                         _ => panic!("Unexpected event"),
8109                 }
8110
8111                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
8112                 nodes[0].node.test_restore_channel_monitor();
8113                 check_added_monitors!(nodes[0], 1);
8114
8115                 let final_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8116                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &final_raa).unwrap();
8117                 check_added_monitors!(nodes[1], 1);
8118
8119                 let mut events = nodes[1].node.get_and_clear_pending_events();
8120                 assert_eq!(events.len(), 1);
8121                 match events[0] {
8122                         Event::PendingHTLCsForwardable { .. } => { },
8123                         _ => panic!("Unexpected event"),
8124                 };
8125                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8126                 nodes[1].node.process_pending_htlc_forwards();
8127
8128                 events = nodes[1].node.get_and_clear_pending_events();
8129                 assert_eq!(events.len(), 1);
8130                 match events[0] {
8131                         Event::PaymentReceived { payment_hash, amt } => {
8132                                 assert_eq!(payment_hash, our_payment_hash);
8133                                 assert_eq!(amt, 1000000);
8134                         },
8135                         _ => panic!("Unexpected event"),
8136                 };
8137
8138                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
8139         }
8140
8141         fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) {
8142                 // Tests handling of a monitor update failure when processing an incoming RAA
8143                 let mut nodes = create_network(3);
8144                 create_announced_chan_between_nodes(&nodes, 0, 1);
8145                 create_announced_chan_between_nodes(&nodes, 1, 2);
8146
8147                 // Rebalance a bit so that we can send backwards from 2 to 1.
8148                 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 5000000);
8149
8150                 // Route a first payment that we'll fail backwards
8151                 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
8152
8153                 // Fail the payment backwards, failing the monitor update on nodes[1]'s receipt of the RAA
8154                 assert!(nodes[2].node.fail_htlc_backwards(&payment_hash_1, PaymentFailReason::PreimageUnknown));
8155                 check_added_monitors!(nodes[2], 1);
8156
8157                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8158                 assert!(updates.update_add_htlcs.is_empty());
8159                 assert!(updates.update_fulfill_htlcs.is_empty());
8160                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8161                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8162                 assert!(updates.update_fee.is_none());
8163                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
8164
8165                 let bs_revoke_and_ack = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
8166                 check_added_monitors!(nodes[0], 0);
8167
8168                 // While the second channel is AwaitingRAA, forward a second payment to get it into the
8169                 // holding cell.
8170                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
8171                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8172                 nodes[0].node.send_payment(route, payment_hash_2).unwrap();
8173                 check_added_monitors!(nodes[0], 1);
8174
8175                 let mut send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8176                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8177                 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false);
8178
8179                 let events_1 = nodes[1].node.get_and_clear_pending_events();
8180                 assert_eq!(events_1.len(), 1);
8181                 match events_1[0] {
8182                         Event::PendingHTLCsForwardable { .. } => { },
8183                         _ => panic!("Unexpected event"),
8184                 };
8185
8186                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8187                 nodes[1].node.process_pending_htlc_forwards();
8188                 check_added_monitors!(nodes[1], 0);
8189                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8190
8191                 // Now fail monitor updating.
8192                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8193                 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() {
8194                         assert_eq!(err, "Failed to update ChannelMonitor");
8195                 } else { panic!(); }
8196                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8197                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8198                 check_added_monitors!(nodes[1], 1);
8199
8200                 // Attempt to forward a third payment but fail due to the second channel being unavailable
8201                 // for forwarding.
8202
8203                 let (_, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
8204                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8205                 nodes[0].node.send_payment(route, payment_hash_3).unwrap();
8206                 check_added_monitors!(nodes[0], 1);
8207
8208                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(()); // We succeed in updating the monitor for the first channel
8209                 send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8210                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8211                 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
8212                 check_added_monitors!(nodes[1], 0);
8213
8214                 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8215                 assert_eq!(events_2.len(), 1);
8216                 match events_2.remove(0) {
8217                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
8218                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8219                                 assert!(updates.update_fulfill_htlcs.is_empty());
8220                                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8221                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8222                                 assert!(updates.update_add_htlcs.is_empty());
8223                                 assert!(updates.update_fee.is_none());
8224
8225                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
8226                                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
8227
8228                                 let events = nodes[0].node.get_and_clear_pending_events();
8229                                 assert_eq!(events.len(), 1);
8230                                 if let Event::PaymentFailed { payment_hash, rejected_by_dest } = events[0] {
8231                                         assert_eq!(payment_hash, payment_hash_3);
8232                                         assert!(!rejected_by_dest);
8233                                 } else { panic!("Unexpected event!"); }
8234                         },
8235                         _ => panic!("Unexpected event type!"),
8236                 };
8237
8238                 let (payment_preimage_4, payment_hash_4) = if test_ignore_second_cs {
8239                         // Try to route another payment backwards from 2 to make sure 1 holds off on responding
8240                         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[0]);
8241                         let route = nodes[2].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8242                         nodes[2].node.send_payment(route, payment_hash_4).unwrap();
8243                         check_added_monitors!(nodes[2], 1);
8244
8245                         send_event = SendEvent::from_event(nodes[2].node.get_and_clear_pending_msg_events().remove(0));
8246                         nodes[1].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8247                         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) {
8248                                 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
8249                         } else { panic!(); }
8250                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8251                         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8252                         (Some(payment_preimage_4), Some(payment_hash_4))
8253                 } else { (None, None) };
8254
8255                 // Restore monitor updating, ensuring we immediately get a fail-back update and a
8256                 // update_add update.
8257                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8258                 nodes[1].node.test_restore_channel_monitor();
8259                 check_added_monitors!(nodes[1], 2);
8260
8261                 let mut events_3 = nodes[1].node.get_and_clear_pending_msg_events();
8262                 if test_ignore_second_cs {
8263                         assert_eq!(events_3.len(), 3);
8264                 } else {
8265                         assert_eq!(events_3.len(), 2);
8266                 }
8267
8268                 // Note that the ordering of the events for different nodes is non-prescriptive, though the
8269                 // ordering of the two events that both go to nodes[2] have to stay in the same order.
8270                 let messages_a = match events_3.pop().unwrap() {
8271                         MessageSendEvent::UpdateHTLCs { node_id, mut updates } => {
8272                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8273                                 assert!(updates.update_fulfill_htlcs.is_empty());
8274                                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8275                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8276                                 assert!(updates.update_add_htlcs.is_empty());
8277                                 assert!(updates.update_fee.is_none());
8278                                 (updates.update_fail_htlcs.remove(0), updates.commitment_signed)
8279                         },
8280                         _ => panic!("Unexpected event type!"),
8281                 };
8282                 let raa = if test_ignore_second_cs {
8283                         match events_3.remove(1) {
8284                                 MessageSendEvent::SendRevokeAndACK { node_id, msg } => {
8285                                         assert_eq!(node_id, nodes[2].node.get_our_node_id());
8286                                         Some(msg.clone())
8287                                 },
8288                                 _ => panic!("Unexpected event"),
8289                         }
8290                 } else { None };
8291                 let send_event_b = SendEvent::from_event(events_3.remove(0));
8292                 assert_eq!(send_event_b.node_id, nodes[2].node.get_our_node_id());
8293
8294                 // Now deliver the new messages...
8295
8296                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &messages_a.0).unwrap();
8297                 commitment_signed_dance!(nodes[0], nodes[1], messages_a.1, false);
8298                 let events_4 = nodes[0].node.get_and_clear_pending_events();
8299                 assert_eq!(events_4.len(), 1);
8300                 if let Event::PaymentFailed { payment_hash, rejected_by_dest } = events_4[0] {
8301                         assert_eq!(payment_hash, payment_hash_1);
8302                         assert!(rejected_by_dest);
8303                 } else { panic!("Unexpected event!"); }
8304
8305                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event_b.msgs[0]).unwrap();
8306                 if test_ignore_second_cs {
8307                         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event_b.commitment_msg).unwrap();
8308                         check_added_monitors!(nodes[2], 1);
8309                         let bs_revoke_and_ack = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8310                         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa.unwrap()).unwrap();
8311                         check_added_monitors!(nodes[2], 1);
8312                         let bs_cs = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8313                         assert!(bs_cs.update_add_htlcs.is_empty());
8314                         assert!(bs_cs.update_fail_htlcs.is_empty());
8315                         assert!(bs_cs.update_fail_malformed_htlcs.is_empty());
8316                         assert!(bs_cs.update_fulfill_htlcs.is_empty());
8317                         assert!(bs_cs.update_fee.is_none());
8318
8319                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
8320                         check_added_monitors!(nodes[1], 1);
8321                         let as_cs = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
8322                         assert!(as_cs.update_add_htlcs.is_empty());
8323                         assert!(as_cs.update_fail_htlcs.is_empty());
8324                         assert!(as_cs.update_fail_malformed_htlcs.is_empty());
8325                         assert!(as_cs.update_fulfill_htlcs.is_empty());
8326                         assert!(as_cs.update_fee.is_none());
8327
8328                         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_cs.commitment_signed).unwrap();
8329                         check_added_monitors!(nodes[1], 1);
8330                         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
8331
8332                         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_cs.commitment_signed).unwrap();
8333                         check_added_monitors!(nodes[2], 1);
8334                         let bs_second_raa = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8335
8336                         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
8337                         check_added_monitors!(nodes[2], 1);
8338                         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
8339
8340                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_second_raa).unwrap();
8341                         check_added_monitors!(nodes[1], 1);
8342                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8343                 } else {
8344                         commitment_signed_dance!(nodes[2], nodes[1], send_event_b.commitment_msg, false);
8345                 }
8346
8347                 let events_5 = nodes[2].node.get_and_clear_pending_events();
8348                 assert_eq!(events_5.len(), 1);
8349                 match events_5[0] {
8350                         Event::PendingHTLCsForwardable { .. } => { },
8351                         _ => panic!("Unexpected event"),
8352                 };
8353
8354                 nodes[2].node.channel_state.lock().unwrap().next_forward = Instant::now();
8355                 nodes[2].node.process_pending_htlc_forwards();
8356
8357                 let events_6 = nodes[2].node.get_and_clear_pending_events();
8358                 assert_eq!(events_6.len(), 1);
8359                 match events_6[0] {
8360                         Event::PaymentReceived { payment_hash, .. } => { assert_eq!(payment_hash, payment_hash_2); },
8361                         _ => panic!("Unexpected event"),
8362                 };
8363
8364                 if test_ignore_second_cs {
8365                         let events_7 = nodes[1].node.get_and_clear_pending_events();
8366                         assert_eq!(events_7.len(), 1);
8367                         match events_7[0] {
8368                                 Event::PendingHTLCsForwardable { .. } => { },
8369                                 _ => panic!("Unexpected event"),
8370                         };
8371
8372                         nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8373                         nodes[1].node.process_pending_htlc_forwards();
8374                         check_added_monitors!(nodes[1], 1);
8375
8376                         send_event = SendEvent::from_node(&nodes[1]);
8377                         assert_eq!(send_event.node_id, nodes[0].node.get_our_node_id());
8378                         assert_eq!(send_event.msgs.len(), 1);
8379                         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8380                         commitment_signed_dance!(nodes[0], nodes[1], send_event.commitment_msg, false);
8381
8382                         let events_8 = nodes[0].node.get_and_clear_pending_events();
8383                         assert_eq!(events_8.len(), 1);
8384                         match events_8[0] {
8385                                 Event::PendingHTLCsForwardable { .. } => { },
8386                                 _ => panic!("Unexpected event"),
8387                         };
8388
8389                         nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
8390                         nodes[0].node.process_pending_htlc_forwards();
8391
8392                         let events_9 = nodes[0].node.get_and_clear_pending_events();
8393                         assert_eq!(events_9.len(), 1);
8394                         match events_9[0] {
8395                                 Event::PaymentReceived { payment_hash, .. } => assert_eq!(payment_hash, payment_hash_4.unwrap()),
8396                                 _ => panic!("Unexpected event"),
8397                         };
8398                         claim_payment(&nodes[2], &[&nodes[1], &nodes[0]], payment_preimage_4.unwrap());
8399                 }
8400
8401                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
8402         }
8403
8404         #[test]
8405         fn test_monitor_update_fail_raa() {
8406                 do_test_monitor_update_fail_raa(false);
8407                 do_test_monitor_update_fail_raa(true);
8408         }
8409
8410         #[test]
8411         fn test_monitor_update_fail_reestablish() {
8412                 // Simple test for message retransmission after monitor update failure on
8413                 // channel_reestablish generating a monitor update (which comes from freeing holding cell
8414                 // HTLCs).
8415                 let mut nodes = create_network(3);
8416                 create_announced_chan_between_nodes(&nodes, 0, 1);
8417                 create_announced_chan_between_nodes(&nodes, 1, 2);
8418
8419                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
8420
8421                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8422                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8423
8424                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
8425                 check_added_monitors!(nodes[2], 1);
8426                 let mut updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8427                 assert!(updates.update_add_htlcs.is_empty());
8428                 assert!(updates.update_fail_htlcs.is_empty());
8429                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8430                 assert!(updates.update_fee.is_none());
8431                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8432                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8433                 check_added_monitors!(nodes[1], 1);
8434                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8435                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
8436
8437                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8438                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8439                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8440
8441                 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
8442                 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8443
8444                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
8445
8446                 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() {
8447                         assert_eq!(err, "Failed to update ChannelMonitor");
8448                 } else { panic!(); }
8449                 check_added_monitors!(nodes[1], 1);
8450
8451                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8452                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8453
8454                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8455                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8456
8457                 assert!(as_reestablish == get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()));
8458                 assert!(bs_reestablish == get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id()));
8459
8460                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
8461
8462                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish).unwrap();
8463                 check_added_monitors!(nodes[1], 0);
8464                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8465
8466                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8467                 nodes[1].node.test_restore_channel_monitor();
8468                 check_added_monitors!(nodes[1], 1);
8469
8470                 updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8471                 assert!(updates.update_add_htlcs.is_empty());
8472                 assert!(updates.update_fail_htlcs.is_empty());
8473                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8474                 assert!(updates.update_fee.is_none());
8475                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8476                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8477                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
8478
8479                 let events = nodes[0].node.get_and_clear_pending_events();
8480                 assert_eq!(events.len(), 1);
8481                 match events[0] {
8482                         Event::PaymentSent { payment_preimage, .. } => assert_eq!(payment_preimage, our_payment_preimage),
8483                         _ => panic!("Unexpected event"),
8484                 }
8485         }
8486
8487         #[test]
8488         fn test_invalid_channel_announcement() {
8489                 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
8490                 let secp_ctx = Secp256k1::new();
8491                 let nodes = create_network(2);
8492
8493                 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1]);
8494
8495                 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8496                 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
8497                 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
8498                 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
8499
8500                 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 } );
8501
8502                 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
8503                 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
8504
8505                 let as_network_key = nodes[0].node.get_our_node_id();
8506                 let bs_network_key = nodes[1].node.get_our_node_id();
8507
8508                 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
8509
8510                 let mut chan_announcement;
8511
8512                 macro_rules! dummy_unsigned_msg {
8513                         () => {
8514                                 msgs::UnsignedChannelAnnouncement {
8515                                         features: msgs::GlobalFeatures::new(),
8516                                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
8517                                         short_channel_id: as_chan.get_short_channel_id().unwrap(),
8518                                         node_id_1: if were_node_one { as_network_key } else { bs_network_key },
8519                                         node_id_2: if were_node_one { bs_network_key } else { as_network_key },
8520                                         bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
8521                                         bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
8522                                         excess_data: Vec::new(),
8523                                 };
8524                         }
8525                 }
8526
8527                 macro_rules! sign_msg {
8528                         ($unsigned_msg: expr) => {
8529                                 let msghash = Message::from_slice(&Sha256dHash::from_data(&$unsigned_msg.encode()[..])[..]).unwrap();
8530                                 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
8531                                 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
8532                                 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].node.our_network_key);
8533                                 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].node.our_network_key);
8534                                 chan_announcement = msgs::ChannelAnnouncement {
8535                                         node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
8536                                         node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
8537                                         bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
8538                                         bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
8539                                         contents: $unsigned_msg
8540                                 }
8541                         }
8542                 }
8543
8544                 let unsigned_msg = dummy_unsigned_msg!();
8545                 sign_msg!(unsigned_msg);
8546                 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
8547                 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 } );
8548
8549                 // Configured with Network::Testnet
8550                 let mut unsigned_msg = dummy_unsigned_msg!();
8551                 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
8552                 sign_msg!(unsigned_msg);
8553                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
8554
8555                 let mut unsigned_msg = dummy_unsigned_msg!();
8556                 unsigned_msg.chain_hash = Sha256dHash::from_data(&[1,2,3,4,5,6,7,8,9]);
8557                 sign_msg!(unsigned_msg);
8558                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
8559         }
8560
8561         struct VecWriter(Vec<u8>);
8562         impl Writer for VecWriter {
8563                 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
8564                         self.0.extend_from_slice(buf);
8565                         Ok(())
8566                 }
8567                 fn size_hint(&mut self, size: usize) {
8568                         self.0.reserve_exact(size);
8569                 }
8570         }
8571
8572         #[test]
8573         fn test_no_txn_manager_serialize_deserialize() {
8574                 let mut nodes = create_network(2);
8575
8576                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
8577
8578                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8579
8580                 let nodes_0_serialized = nodes[0].node.encode();
8581                 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8582                 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8583
8584                 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())));
8585                 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8586                 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8587                 assert!(chan_0_monitor_read.is_empty());
8588
8589                 let mut nodes_0_read = &nodes_0_serialized[..];
8590                 let config = UserConfig::new();
8591                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8592                 let (_, nodes_0_deserialized) = {
8593                         let mut channel_monitors = HashMap::new();
8594                         channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8595                         <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8596                                 default_config: config,
8597                                 keys_manager,
8598                                 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8599                                 monitor: nodes[0].chan_monitor.clone(),
8600                                 chain_monitor: nodes[0].chain_monitor.clone(),
8601                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8602                                 logger: Arc::new(test_utils::TestLogger::new()),
8603                                 channel_monitors: &channel_monitors,
8604                         }).unwrap()
8605                 };
8606                 assert!(nodes_0_read.is_empty());
8607
8608                 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8609                 nodes[0].node = Arc::new(nodes_0_deserialized);
8610                 let nodes_0_as_listener: Arc<ChainListener> = nodes[0].node.clone();
8611                 nodes[0].chain_monitor.register_listener(Arc::downgrade(&nodes_0_as_listener));
8612                 assert_eq!(nodes[0].node.list_channels().len(), 1);
8613                 check_added_monitors!(nodes[0], 1);
8614
8615                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8616                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
8617                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8618                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
8619
8620                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
8621                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8622                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
8623                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8624
8625                 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8626                 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8627                 for node in nodes.iter() {
8628                         assert!(node.router.handle_channel_announcement(&announcement).unwrap());
8629                         node.router.handle_channel_update(&as_update).unwrap();
8630                         node.router.handle_channel_update(&bs_update).unwrap();
8631                 }
8632
8633                 send_payment(&nodes[0], &[&nodes[1]], 1000000);
8634         }
8635
8636         #[test]
8637         fn test_simple_manager_serialize_deserialize() {
8638                 let mut nodes = create_network(2);
8639                 create_announced_chan_between_nodes(&nodes, 0, 1);
8640
8641                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8642                 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8643
8644                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8645
8646                 let nodes_0_serialized = nodes[0].node.encode();
8647                 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8648                 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8649
8650                 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())));
8651                 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8652                 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8653                 assert!(chan_0_monitor_read.is_empty());
8654
8655                 let mut nodes_0_read = &nodes_0_serialized[..];
8656                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8657                 let (_, nodes_0_deserialized) = {
8658                         let mut channel_monitors = HashMap::new();
8659                         channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8660                         <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8661                                 default_config: UserConfig::new(),
8662                                 keys_manager,
8663                                 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8664                                 monitor: nodes[0].chan_monitor.clone(),
8665                                 chain_monitor: nodes[0].chain_monitor.clone(),
8666                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8667                                 logger: Arc::new(test_utils::TestLogger::new()),
8668                                 channel_monitors: &channel_monitors,
8669                         }).unwrap()
8670                 };
8671                 assert!(nodes_0_read.is_empty());
8672
8673                 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8674                 nodes[0].node = Arc::new(nodes_0_deserialized);
8675                 check_added_monitors!(nodes[0], 1);
8676
8677                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8678
8679                 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
8680                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
8681         }
8682
8683         #[test]
8684         fn test_manager_serialize_deserialize_inconsistent_monitor() {
8685                 // Test deserializing a ChannelManager with a out-of-date ChannelMonitor
8686                 let mut nodes = create_network(4);
8687                 create_announced_chan_between_nodes(&nodes, 0, 1);
8688                 create_announced_chan_between_nodes(&nodes, 2, 0);
8689                 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3);
8690
8691                 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
8692
8693                 // Serialize the ChannelManager here, but the monitor we keep up-to-date
8694                 let nodes_0_serialized = nodes[0].node.encode();
8695
8696                 route_payment(&nodes[0], &[&nodes[3]], 1000000);
8697                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8698                 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8699                 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8700
8701                 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
8702                 // nodes[3])
8703                 let mut node_0_monitors_serialized = Vec::new();
8704                 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
8705                         let mut writer = VecWriter(Vec::new());
8706                         monitor.1.write_for_disk(&mut writer).unwrap();
8707                         node_0_monitors_serialized.push(writer.0);
8708                 }
8709
8710                 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())));
8711                 let mut node_0_monitors = Vec::new();
8712                 for serialized in node_0_monitors_serialized.iter() {
8713                         let mut read = &serialized[..];
8714                         let (_, monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
8715                         assert!(read.is_empty());
8716                         node_0_monitors.push(monitor);
8717                 }
8718
8719                 let mut nodes_0_read = &nodes_0_serialized[..];
8720                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8721                 let (_, nodes_0_deserialized) = <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8722                         default_config: UserConfig::new(),
8723                         keys_manager,
8724                         fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8725                         monitor: nodes[0].chan_monitor.clone(),
8726                         chain_monitor: nodes[0].chain_monitor.clone(),
8727                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8728                         logger: Arc::new(test_utils::TestLogger::new()),
8729                         channel_monitors: &node_0_monitors.iter().map(|monitor| { (monitor.get_funding_txo().unwrap(), monitor) }).collect(),
8730                 }).unwrap();
8731                 assert!(nodes_0_read.is_empty());
8732
8733                 { // Channel close should result in a commitment tx and an HTLC tx
8734                         let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8735                         assert_eq!(txn.len(), 2);
8736                         assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
8737                         assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
8738                 }
8739
8740                 for monitor in node_0_monitors.drain(..) {
8741                         assert!(nodes[0].chan_monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor).is_ok());
8742                         check_added_monitors!(nodes[0], 1);
8743                 }
8744                 nodes[0].node = Arc::new(nodes_0_deserialized);
8745
8746                 // nodes[1] and nodes[2] have no lost state with nodes[0]...
8747                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8748                 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8749                 //... and we can even still claim the payment!
8750                 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
8751
8752                 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id());
8753                 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8754                 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id());
8755                 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) {
8756                         assert_eq!(msg.channel_id, channel_id);
8757                 } else { panic!("Unexpected result"); }
8758         }
8759
8760         macro_rules! check_spendable_outputs {
8761                 ($node: expr, $der_idx: expr) => {
8762                         {
8763                                 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
8764                                 let mut txn = Vec::new();
8765                                 for event in events {
8766                                         match event {
8767                                                 Event::SpendableOutputs { ref outputs } => {
8768                                                         for outp in outputs {
8769                                                                 match *outp {
8770                                                                         SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
8771                                                                                 let input = TxIn {
8772                                                                                         previous_output: outpoint.clone(),
8773                                                                                         script_sig: Script::new(),
8774                                                                                         sequence: 0,
8775                                                                                         witness: Vec::new(),
8776                                                                                 };
8777                                                                                 let outp = TxOut {
8778                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8779                                                                                         value: output.value,
8780                                                                                 };
8781                                                                                 let mut spend_tx = Transaction {
8782                                                                                         version: 2,
8783                                                                                         lock_time: 0,
8784                                                                                         input: vec![input],
8785                                                                                         output: vec![outp],
8786                                                                                 };
8787                                                                                 let secp_ctx = Secp256k1::new();
8788                                                                                 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
8789                                                                                 let witness_script = Address::p2pkh(&remotepubkey, Network::Testnet).script_pubkey();
8790                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8791                                                                                 let remotesig = secp_ctx.sign(&sighash, key);
8792                                                                                 spend_tx.input[0].witness.push(remotesig.serialize_der(&secp_ctx).to_vec());
8793                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8794                                                                                 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
8795                                                                                 txn.push(spend_tx);
8796                                                                         },
8797                                                                         SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
8798                                                                                 let input = TxIn {
8799                                                                                         previous_output: outpoint.clone(),
8800                                                                                         script_sig: Script::new(),
8801                                                                                         sequence: *to_self_delay as u32,
8802                                                                                         witness: Vec::new(),
8803                                                                                 };
8804                                                                                 let outp = TxOut {
8805                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8806                                                                                         value: output.value,
8807                                                                                 };
8808                                                                                 let mut spend_tx = Transaction {
8809                                                                                         version: 2,
8810                                                                                         lock_time: 0,
8811                                                                                         input: vec![input],
8812                                                                                         output: vec![outp],
8813                                                                                 };
8814                                                                                 let secp_ctx = Secp256k1::new();
8815                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
8816                                                                                 let local_delaysig = secp_ctx.sign(&sighash, key);
8817                                                                                 spend_tx.input[0].witness.push(local_delaysig.serialize_der(&secp_ctx).to_vec());
8818                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8819                                                                                 spend_tx.input[0].witness.push(vec!(0));
8820                                                                                 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
8821                                                                                 txn.push(spend_tx);
8822                                                                         },
8823                                                                         SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
8824                                                                                 let secp_ctx = Secp256k1::new();
8825                                                                                 let input = TxIn {
8826                                                                                         previous_output: outpoint.clone(),
8827                                                                                         script_sig: Script::new(),
8828                                                                                         sequence: 0,
8829                                                                                         witness: Vec::new(),
8830                                                                                 };
8831                                                                                 let outp = TxOut {
8832                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8833                                                                                         value: output.value,
8834                                                                                 };
8835                                                                                 let mut spend_tx = Transaction {
8836                                                                                         version: 2,
8837                                                                                         lock_time: 0,
8838                                                                                         input: vec![input],
8839                                                                                         output: vec![outp.clone()],
8840                                                                                 };
8841                                                                                 let secret = {
8842                                                                                         match ExtendedPrivKey::new_master(&secp_ctx, Network::Testnet, &$node.node_seed) {
8843                                                                                                 Ok(master_key) => {
8844                                                                                                         match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx)) {
8845                                                                                                                 Ok(key) => key,
8846                                                                                                                 Err(_) => panic!("Your RNG is busted"),
8847                                                                                                         }
8848                                                                                                 }
8849                                                                                                 Err(_) => panic!("Your rng is busted"),
8850                                                                                         }
8851                                                                                 };
8852                                                                                 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
8853                                                                                 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
8854                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8855                                                                                 let sig = secp_ctx.sign(&sighash, &secret.secret_key);
8856                                                                                 spend_tx.input[0].witness.push(sig.serialize_der(&secp_ctx).to_vec());
8857                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8858                                                                                 spend_tx.input[0].witness.push(pubkey.serialize().to_vec());
8859                                                                                 txn.push(spend_tx);
8860                                                                         },
8861                                                                 }
8862                                                         }
8863                                                 },
8864                                                 _ => panic!("Unexpected event"),
8865                                         };
8866                                 }
8867                                 txn
8868                         }
8869                 }
8870         }
8871
8872         #[test]
8873         fn test_claim_sizeable_push_msat() {
8874                 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
8875                 let nodes = create_network(2);
8876
8877                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8878                 nodes[1].node.force_close_channel(&chan.2);
8879                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8880                 match events[0] {
8881                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8882                         _ => panic!("Unexpected event"),
8883                 }
8884                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8885                 assert_eq!(node_txn.len(), 1);
8886                 check_spends!(node_txn[0], chan.3.clone());
8887                 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
8888
8889                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8890                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8891                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8892                 assert_eq!(spend_txn.len(), 1);
8893                 check_spends!(spend_txn[0], node_txn[0].clone());
8894         }
8895
8896         #[test]
8897         fn test_claim_on_remote_sizeable_push_msat() {
8898                 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8899                 // to_remote output is encumbered by a P2WPKH
8900
8901                 let nodes = create_network(2);
8902
8903                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8904                 nodes[0].node.force_close_channel(&chan.2);
8905                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8906                 match events[0] {
8907                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8908                         _ => panic!("Unexpected event"),
8909                 }
8910                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8911                 assert_eq!(node_txn.len(), 1);
8912                 check_spends!(node_txn[0], chan.3.clone());
8913                 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
8914
8915                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8916                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8917                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8918                 match events[0] {
8919                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8920                         _ => panic!("Unexpected event"),
8921                 }
8922                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8923                 assert_eq!(spend_txn.len(), 2);
8924                 assert_eq!(spend_txn[0], spend_txn[1]);
8925                 check_spends!(spend_txn[0], node_txn[0].clone());
8926         }
8927
8928         #[test]
8929         fn test_claim_on_remote_revoked_sizeable_push_msat() {
8930                 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8931                 // to_remote output is encumbered by a P2WPKH
8932
8933                 let nodes = create_network(2);
8934
8935                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
8936                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8937                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
8938                 assert_eq!(revoked_local_txn[0].input.len(), 1);
8939                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8940
8941                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8942                 let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8943                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
8944                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8945                 match events[0] {
8946                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8947                         _ => panic!("Unexpected event"),
8948                 }
8949                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8950                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8951                 assert_eq!(spend_txn.len(), 4);
8952                 assert_eq!(spend_txn[0], spend_txn[2]); // to_remote output on revoked remote commitment_tx
8953                 check_spends!(spend_txn[0], revoked_local_txn[0].clone());
8954                 assert_eq!(spend_txn[1], spend_txn[3]); // to_local output on local commitment tx
8955                 check_spends!(spend_txn[1], node_txn[0].clone());
8956         }
8957
8958         #[test]
8959         fn test_static_spendable_outputs_preimage_tx() {
8960                 let nodes = create_network(2);
8961
8962                 // Create some initial channels
8963                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8964
8965                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8966
8967                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8968                 assert_eq!(commitment_tx[0].input.len(), 1);
8969                 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
8970
8971                 // Settle A's commitment tx on B's chain
8972                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8973                 assert!(nodes[1].node.claim_funds(payment_preimage));
8974                 check_added_monitors!(nodes[1], 1);
8975                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
8976                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8977                 match events[0] {
8978                         MessageSendEvent::UpdateHTLCs { .. } => {},
8979                         _ => panic!("Unexpected event"),
8980                 }
8981                 match events[1] {
8982                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8983                         _ => panic!("Unexepected event"),
8984                 }
8985
8986                 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
8987                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 1 (local commitment tx), ChannelMonitor: 2 (1 preimage tx) * 2 (block-rescan)
8988                 check_spends!(node_txn[0], commitment_tx[0].clone());
8989                 assert_eq!(node_txn[0], node_txn[2]);
8990                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8991                 check_spends!(node_txn[1], chan_1.3.clone());
8992
8993                 let spend_txn = check_spendable_outputs!(nodes[1], 1); // , 0, 0, 1, 1);
8994                 assert_eq!(spend_txn.len(), 2);
8995                 assert_eq!(spend_txn[0], spend_txn[1]);
8996                 check_spends!(spend_txn[0], node_txn[0].clone());
8997         }
8998
8999         #[test]
9000         fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
9001                 let nodes = create_network(2);
9002
9003                 // Create some initial channels
9004                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9005
9006                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9007                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
9008                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9009                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9010
9011                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9012
9013                 let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9014                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9015                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9016                 match events[0] {
9017                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9018                         _ => panic!("Unexpected event"),
9019                 }
9020                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9021                 assert_eq!(node_txn.len(), 3);
9022                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]);
9023                 assert_eq!(node_txn[0].input.len(), 2);
9024                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
9025
9026                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9027                 assert_eq!(spend_txn.len(), 2);
9028                 assert_eq!(spend_txn[0], spend_txn[1]);
9029                 check_spends!(spend_txn[0], node_txn[0].clone());
9030         }
9031
9032         #[test]
9033         fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
9034                 let nodes = create_network(2);
9035
9036                 // Create some initial channels
9037                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9038
9039                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9040                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9041                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9042                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9043
9044                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9045
9046                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9047                 // A will generate HTLC-Timeout from revoked commitment tx
9048                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9049                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9050                 match events[0] {
9051                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9052                         _ => panic!("Unexpected event"),
9053                 }
9054                 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9055                 assert_eq!(revoked_htlc_txn.len(), 3);
9056                 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
9057                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
9058                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9059                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
9060                 check_spends!(revoked_htlc_txn[1], chan_1.3.clone());
9061
9062                 // B will generate justice tx from A's revoked commitment/HTLC tx
9063                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
9064                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9065                 match events[0] {
9066                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9067                         _ => panic!("Unexpected event"),
9068                 }
9069
9070                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9071                 assert_eq!(node_txn.len(), 4);
9072                 assert_eq!(node_txn[3].input.len(), 1);
9073                 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
9074
9075                 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
9076                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9077                 assert_eq!(spend_txn.len(), 3);
9078                 assert_eq!(spend_txn[0], spend_txn[1]);
9079                 check_spends!(spend_txn[0], node_txn[0].clone());
9080                 check_spends!(spend_txn[2], node_txn[3].clone());
9081         }
9082
9083         #[test]
9084         fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
9085                 let nodes = create_network(2);
9086
9087                 // Create some initial channels
9088                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9089
9090                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9091                 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9092                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9093                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9094
9095                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9096
9097                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9098                 // B will generate HTLC-Success from revoked commitment tx
9099                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9100                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9101                 match events[0] {
9102                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9103                         _ => panic!("Unexpected event"),
9104                 }
9105                 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9106
9107                 assert_eq!(revoked_htlc_txn.len(), 3);
9108                 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
9109                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
9110                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9111                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
9112
9113                 // A will generate justice tx from B's revoked commitment/HTLC tx
9114                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
9115                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9116                 match events[0] {
9117                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9118                         _ => panic!("Unexpected event"),
9119                 }
9120
9121                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9122                 assert_eq!(node_txn.len(), 4);
9123                 assert_eq!(node_txn[3].input.len(), 1);
9124                 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
9125
9126                 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
9127                 let spend_txn = check_spendable_outputs!(nodes[0], 1);
9128                 assert_eq!(spend_txn.len(), 5);
9129                 assert_eq!(spend_txn[0], spend_txn[2]);
9130                 assert_eq!(spend_txn[1], spend_txn[3]);
9131                 check_spends!(spend_txn[0], revoked_local_txn[0].clone()); // spending to_remote output from revoked local tx
9132                 check_spends!(spend_txn[1], node_txn[2].clone()); // spending justice tx output from revoked local tx htlc received output
9133                 check_spends!(spend_txn[4], node_txn[3].clone()); // spending justice tx output on htlc success tx
9134         }
9135
9136         #[test]
9137         fn test_onchain_to_onchain_claim() {
9138                 // Test that in case of channel closure, we detect the state of output thanks to
9139                 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
9140                 // First, have C claim an HTLC against its own latest commitment transaction.
9141                 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
9142                 // channel.
9143                 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
9144                 // gets broadcast.
9145
9146                 let nodes = create_network(3);
9147
9148                 // Create some initial channels
9149                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9150                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
9151
9152                 // Rebalance the network a bit by relaying one payment through all the channels ...
9153                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
9154                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
9155
9156                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
9157                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9158                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
9159                 check_spends!(commitment_tx[0], chan_2.3.clone());
9160                 nodes[2].node.claim_funds(payment_preimage);
9161                 check_added_monitors!(nodes[2], 1);
9162                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9163                 assert!(updates.update_add_htlcs.is_empty());
9164                 assert!(updates.update_fail_htlcs.is_empty());
9165                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
9166                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9167
9168                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
9169                 let events = nodes[2].node.get_and_clear_pending_msg_events();
9170                 assert_eq!(events.len(), 1);
9171                 match events[0] {
9172                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9173                         _ => panic!("Unexpected event"),
9174                 }
9175
9176                 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
9177                 assert_eq!(c_txn.len(), 3);
9178                 assert_eq!(c_txn[0], c_txn[2]);
9179                 assert_eq!(commitment_tx[0], c_txn[1]);
9180                 check_spends!(c_txn[1], chan_2.3.clone());
9181                 check_spends!(c_txn[2], c_txn[1].clone());
9182                 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
9183                 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9184                 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
9185                 assert_eq!(c_txn[0].lock_time, 0); // Success tx
9186
9187                 // 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
9188                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
9189                 {
9190                         let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9191                         assert_eq!(b_txn.len(), 4);
9192                         assert_eq!(b_txn[0], b_txn[3]);
9193                         check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
9194                         check_spends!(b_txn[2], b_txn[1].clone()); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
9195                         assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9196                         assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
9197                         assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
9198                         check_spends!(b_txn[0], c_txn[1].clone()); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
9199                         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9200                         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
9201                         assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
9202                         b_txn.clear();
9203                 }
9204                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
9205                 check_added_monitors!(nodes[1], 1);
9206                 match msg_events[0] {
9207                         MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
9208                         _ => panic!("Unexpected event"),
9209                 }
9210                 match msg_events[1] {
9211                         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, .. } } => {
9212                                 assert!(update_add_htlcs.is_empty());
9213                                 assert!(update_fail_htlcs.is_empty());
9214                                 assert_eq!(update_fulfill_htlcs.len(), 1);
9215                                 assert!(update_fail_malformed_htlcs.is_empty());
9216                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
9217                         },
9218                         _ => panic!("Unexpected event"),
9219                 };
9220                 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
9221                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9222                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
9223                 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9224                 assert_eq!(b_txn.len(), 3);
9225                 check_spends!(b_txn[1], chan_1.3); // Local commitment tx, issued by ChannelManager
9226                 assert_eq!(b_txn[0], b_txn[2]); // HTLC-Success tx, issued by ChannelMonitor, * 2 due to block rescan
9227                 check_spends!(b_txn[0], commitment_tx[0].clone());
9228                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9229                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
9230                 assert_eq!(b_txn[2].lock_time, 0); // Success tx
9231                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
9232                 match msg_events[0] {
9233                         MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
9234                         _ => panic!("Unexpected event"),
9235                 }
9236         }
9237
9238         #[test]
9239         fn test_duplicate_payment_hash_one_failure_one_success() {
9240                 // Topology : A --> B --> C
9241                 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
9242                 let mut nodes = create_network(3);
9243
9244                 create_announced_chan_between_nodes(&nodes, 0, 1);
9245                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
9246
9247                 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
9248                 *nodes[0].network_payment_count.borrow_mut() -= 1;
9249                 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
9250
9251                 let commitment_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
9252                 assert_eq!(commitment_txn[0].input.len(), 1);
9253                 check_spends!(commitment_txn[0], chan_2.3.clone());
9254
9255                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9256                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
9257                 let htlc_timeout_tx;
9258                 { // Extract one of the two HTLC-Timeout transaction
9259                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9260                         assert_eq!(node_txn.len(), 7);
9261                         assert_eq!(node_txn[0], node_txn[5]);
9262                         assert_eq!(node_txn[1], node_txn[6]);
9263                         check_spends!(node_txn[0], commitment_txn[0].clone());
9264                         assert_eq!(node_txn[0].input.len(), 1);
9265                         check_spends!(node_txn[1], commitment_txn[0].clone());
9266                         assert_eq!(node_txn[1].input.len(), 1);
9267                         assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
9268                         check_spends!(node_txn[2], chan_2.3.clone());
9269                         check_spends!(node_txn[3], node_txn[2].clone());
9270                         check_spends!(node_txn[4], node_txn[2].clone());
9271                         htlc_timeout_tx = node_txn[1].clone();
9272                 }
9273
9274                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9275                 match events[0] {
9276                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9277                         _ => panic!("Unexepected event"),
9278                 }
9279
9280                 nodes[2].node.claim_funds(our_payment_preimage);
9281                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
9282                 check_added_monitors!(nodes[2], 2);
9283                 let events = nodes[2].node.get_and_clear_pending_msg_events();
9284                 match events[0] {
9285                         MessageSendEvent::UpdateHTLCs { .. } => {},
9286                         _ => panic!("Unexpected event"),
9287                 }
9288                 match events[1] {
9289                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9290                         _ => panic!("Unexepected event"),
9291                 }
9292                 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9293                 assert_eq!(htlc_success_txn.len(), 5);
9294                 check_spends!(htlc_success_txn[2], chan_2.3.clone());
9295                 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
9296                 assert_eq!(htlc_success_txn[0].input.len(), 1);
9297                 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9298                 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
9299                 assert_eq!(htlc_success_txn[1].input.len(), 1);
9300                 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9301                 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
9302                 check_spends!(htlc_success_txn[0], commitment_txn[0].clone());
9303                 check_spends!(htlc_success_txn[1], commitment_txn[0].clone());
9304
9305                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
9306                 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9307                 assert!(htlc_updates.update_add_htlcs.is_empty());
9308                 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
9309                 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
9310                 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
9311                 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
9312                 check_added_monitors!(nodes[1], 1);
9313
9314                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]).unwrap();
9315                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9316                 {
9317                         commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
9318                         let events = nodes[0].node.get_and_clear_pending_msg_events();
9319                         assert_eq!(events.len(), 1);
9320                         match events[0] {
9321                                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
9322                                 },
9323                                 _ => { panic!("Unexpected event"); }
9324                         }
9325                 }
9326                 let events = nodes[0].node.get_and_clear_pending_events();
9327                 match events[0] {
9328                         Event::PaymentFailed { ref payment_hash, .. } => {
9329                                 assert_eq!(*payment_hash, duplicate_payment_hash);
9330                         }
9331                         _ => panic!("Unexpected event"),
9332                 }
9333
9334                 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
9335                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
9336                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9337                 assert!(updates.update_add_htlcs.is_empty());
9338                 assert!(updates.update_fail_htlcs.is_empty());
9339                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
9340                 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
9341                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9342                 check_added_monitors!(nodes[1], 1);
9343
9344                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
9345                 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
9346
9347                 let events = nodes[0].node.get_and_clear_pending_events();
9348                 match events[0] {
9349                         Event::PaymentSent { ref payment_preimage } => {
9350                                 assert_eq!(*payment_preimage, our_payment_preimage);
9351                         }
9352                         _ => panic!("Unexpected event"),
9353                 }
9354         }
9355
9356         #[test]
9357         fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
9358                 let nodes = create_network(2);
9359
9360                 // Create some initial channels
9361                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9362
9363                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
9364                 let local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9365                 assert_eq!(local_txn[0].input.len(), 1);
9366                 check_spends!(local_txn[0], chan_1.3.clone());
9367
9368                 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
9369                 nodes[1].node.claim_funds(payment_preimage);
9370                 check_added_monitors!(nodes[1], 1);
9371                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9372                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
9373                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9374                 match events[0] {
9375                         MessageSendEvent::UpdateHTLCs { .. } => {},
9376                         _ => panic!("Unexpected event"),
9377                 }
9378                 match events[1] {
9379                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9380                         _ => panic!("Unexepected event"),
9381                 }
9382                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9383                 assert_eq!(node_txn[0].input.len(), 1);
9384                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9385                 check_spends!(node_txn[0], local_txn[0].clone());
9386
9387                 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
9388                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9389                 assert_eq!(spend_txn.len(), 2);
9390                 check_spends!(spend_txn[0], node_txn[0].clone());
9391                 check_spends!(spend_txn[1], node_txn[2].clone());
9392         }
9393
9394         #[test]
9395         fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
9396                 let nodes = create_network(2);
9397
9398                 // Create some initial channels
9399                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9400
9401                 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
9402                 let local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9403                 assert_eq!(local_txn[0].input.len(), 1);
9404                 check_spends!(local_txn[0], chan_1.3.clone());
9405
9406                 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
9407                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9408                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
9409                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9410                 match events[0] {
9411                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9412                         _ => panic!("Unexepected event"),
9413                 }
9414                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9415                 assert_eq!(node_txn[0].input.len(), 1);
9416                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9417                 check_spends!(node_txn[0], local_txn[0].clone());
9418
9419                 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
9420                 let spend_txn = check_spendable_outputs!(nodes[0], 1);
9421                 assert_eq!(spend_txn.len(), 8);
9422                 assert_eq!(spend_txn[0], spend_txn[2]);
9423                 assert_eq!(spend_txn[0], spend_txn[4]);
9424                 assert_eq!(spend_txn[0], spend_txn[6]);
9425                 assert_eq!(spend_txn[1], spend_txn[3]);
9426                 assert_eq!(spend_txn[1], spend_txn[5]);
9427                 assert_eq!(spend_txn[1], spend_txn[7]);
9428                 check_spends!(spend_txn[0], local_txn[0].clone());
9429                 check_spends!(spend_txn[1], node_txn[0].clone());
9430         }
9431
9432         #[test]
9433         fn test_static_output_closing_tx() {
9434                 let nodes = create_network(2);
9435
9436                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
9437
9438                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
9439                 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
9440
9441                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9442                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
9443                 let spend_txn = check_spendable_outputs!(nodes[0], 2);
9444                 assert_eq!(spend_txn.len(), 1);
9445                 check_spends!(spend_txn[0], closing_tx.clone());
9446
9447                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
9448                 let spend_txn = check_spendable_outputs!(nodes[1], 2);
9449                 assert_eq!(spend_txn.len(), 1);
9450                 check_spends!(spend_txn[0], closing_tx);
9451         }
9452 }