Add TODO noting confusion over |20 (channel_disabled) definition
[rust-lightning] / src / ln / channelmanager.rs
1 //! The top-level channel management and payment tracking stuff lives here.
2 //!
3 //! The ChannelManager is the main chunk of logic implementing the lightning protocol and is
4 //! responsible for tracking which channels are open, HTLCs are in flight and reestablishing those
5 //! upon reconnect to the relevant peer(s).
6 //!
7 //! It does not manage routing logic (see ln::router for that) nor does it manage constructing
8 //! on-chain transactions (it only monitors the chain to watch for any force-closes that might
9 //! imply it needs to fail HTLCs/payments/channels it manages).
10
11 use bitcoin::blockdata::block::BlockHeader;
12 use bitcoin::blockdata::transaction::Transaction;
13 use bitcoin::blockdata::constants::genesis_block;
14 use bitcoin::network::constants::Network;
15 use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
16
17 use secp256k1::key::{SecretKey,PublicKey};
18 use secp256k1::{Secp256k1,Message};
19 use secp256k1::ecdh::SharedSecret;
20 use secp256k1;
21
22 use chain::chaininterface::{BroadcasterInterface,ChainListener,ChainWatchInterface,FeeEstimator};
23 use chain::transaction::OutPoint;
24 use ln::channel::{Channel, ChannelError};
25 use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, ManyChannelMonitor, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, HTLC_FAIL_ANTI_REORG_DELAY};
26 use ln::router::{Route,RouteHop};
27 use ln::msgs;
28 use ln::msgs::{ChannelMessageHandler, DecodeError, HandleError};
29 use chain::keysinterface::KeysInterface;
30 use util::config::UserConfig;
31 use util::{byte_utils, events, internal_traits, rng};
32 use util::sha2::Sha256;
33 use util::ser::{Readable, ReadableArgs, Writeable, Writer};
34 use util::chacha20poly1305rfc::ChaCha20;
35 use util::logger::Logger;
36 use util::errors::APIError;
37 use util::errors;
38
39 use crypto;
40 use crypto::mac::{Mac,MacResult};
41 use crypto::hmac::Hmac;
42 use crypto::digest::Digest;
43 use crypto::symmetriccipher::SynchronousStreamCipher;
44
45 use std::{cmp, ptr, mem};
46 use std::collections::{HashMap, hash_map, HashSet};
47 use std::io::Cursor;
48 use std::sync::{Arc, Mutex, MutexGuard, RwLock};
49 use std::sync::atomic::{AtomicUsize, Ordering};
50 use std::time::{Instant,Duration};
51
52 /// We hold various information about HTLC relay in the HTLC objects in Channel itself:
53 ///
54 /// Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
55 /// forward the HTLC with information it will give back to us when it does so, or if it should Fail
56 /// the HTLC with the relevant message for the Channel to handle giving to the remote peer.
57 ///
58 /// When a Channel forwards an HTLC to its peer, it will give us back the PendingForwardHTLCInfo
59 /// which we will use to construct an outbound HTLC, with a relevant HTLCSource::PreviousHopData
60 /// filled in to indicate where it came from (which we can use to either fail-backwards or fulfill
61 /// the HTLC backwards along the relevant path).
62 /// Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
63 /// our payment, which we can use to decode errors or inform the user that the payment was sent.
64 mod channel_held_info {
65         use ln::msgs;
66         use ln::router::Route;
67         use ln::channelmanager::PaymentHash;
68         use secp256k1::key::SecretKey;
69
70         /// Stores the info we will need to send when we want to forward an HTLC onwards
71         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
72         pub struct PendingForwardHTLCInfo {
73                 pub(super) onion_packet: Option<msgs::OnionPacket>,
74                 pub(super) incoming_shared_secret: [u8; 32],
75                 pub(super) payment_hash: PaymentHash,
76                 pub(super) short_channel_id: u64,
77                 pub(super) amt_to_forward: u64,
78                 pub(super) outgoing_cltv_value: u32,
79         }
80
81         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
82         pub enum HTLCFailureMsg {
83                 Relay(msgs::UpdateFailHTLC),
84                 Malformed(msgs::UpdateFailMalformedHTLC),
85         }
86
87         /// Stores whether we can't forward an HTLC or relevant forwarding info
88         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
89         pub enum PendingHTLCStatus {
90                 Forward(PendingForwardHTLCInfo),
91                 Fail(HTLCFailureMsg),
92         }
93
94         /// Tracks the inbound corresponding to an outbound HTLC
95         #[derive(Clone, PartialEq)]
96         pub struct HTLCPreviousHopData {
97                 pub(super) short_channel_id: u64,
98                 pub(super) htlc_id: u64,
99                 pub(super) incoming_packet_shared_secret: [u8; 32],
100         }
101
102         /// Tracks the inbound corresponding to an outbound HTLC
103         #[derive(Clone, PartialEq)]
104         pub enum HTLCSource {
105                 PreviousHopData(HTLCPreviousHopData),
106                 OutboundRoute {
107                         route: Route,
108                         session_priv: SecretKey,
109                         /// Technically we can recalculate this from the route, but we cache it here to avoid
110                         /// doing a double-pass on route when we get a failure back
111                         first_hop_htlc_msat: u64,
112                 },
113         }
114         #[cfg(test)]
115         impl HTLCSource {
116                 pub fn dummy() -> Self {
117                         HTLCSource::OutboundRoute {
118                                 route: Route { hops: Vec::new() },
119                                 session_priv: SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[1; 32]).unwrap(),
120                                 first_hop_htlc_msat: 0,
121                         }
122                 }
123         }
124
125         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
126         pub(crate) enum HTLCFailReason {
127                 ErrorPacket {
128                         err: msgs::OnionErrorPacket,
129                 },
130                 Reason {
131                         failure_code: u16,
132                         data: Vec<u8>,
133                 }
134         }
135 }
136 pub(super) use self::channel_held_info::*;
137
138 /// payment_hash type, use to cross-lock hop
139 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
140 pub struct PaymentHash(pub [u8;32]);
141 /// payment_preimage type, use to route payment between hop
142 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
143 pub struct PaymentPreimage(pub [u8;32]);
144
145 type ShutdownResult = (Vec<Transaction>, Vec<(HTLCSource, PaymentHash)>);
146
147 /// Error type returned across the channel_state mutex boundary. When an Err is generated for a
148 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
149 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
150 /// channel_state lock. We then return the set of things that need to be done outside the lock in
151 /// this struct and call handle_error!() on it.
152
153 struct MsgHandleErrInternal {
154         err: msgs::HandleError,
155         shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
156 }
157 impl MsgHandleErrInternal {
158         #[inline]
159         fn send_err_msg_no_close(err: &'static str, channel_id: [u8; 32]) -> Self {
160                 Self {
161                         err: HandleError {
162                                 err,
163                                 action: Some(msgs::ErrorAction::SendErrorMessage {
164                                         msg: msgs::ErrorMessage {
165                                                 channel_id,
166                                                 data: err.to_string()
167                                         },
168                                 }),
169                         },
170                         shutdown_finish: None,
171                 }
172         }
173         #[inline]
174         fn from_no_close(err: msgs::HandleError) -> Self {
175                 Self { err, shutdown_finish: None }
176         }
177         #[inline]
178         fn from_finish_shutdown(err: &'static str, channel_id: [u8; 32], shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
179                 Self {
180                         err: HandleError {
181                                 err,
182                                 action: Some(msgs::ErrorAction::SendErrorMessage {
183                                         msg: msgs::ErrorMessage {
184                                                 channel_id,
185                                                 data: err.to_string()
186                                         },
187                                 }),
188                         },
189                         shutdown_finish: Some((shutdown_res, channel_update)),
190                 }
191         }
192         #[inline]
193         fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
194                 Self {
195                         err: match err {
196                                 ChannelError::Ignore(msg) => HandleError {
197                                         err: msg,
198                                         action: Some(msgs::ErrorAction::IgnoreError),
199                                 },
200                                 ChannelError::Close(msg) => HandleError {
201                                         err: msg,
202                                         action: Some(msgs::ErrorAction::SendErrorMessage {
203                                                 msg: msgs::ErrorMessage {
204                                                         channel_id,
205                                                         data: msg.to_string()
206                                                 },
207                                         }),
208                                 },
209                         },
210                         shutdown_finish: None,
211                 }
212         }
213 }
214
215 /// Pass to fail_htlc_backwwards to indicate the reason to fail the payment
216 /// after a PaymentReceived event.
217 #[derive(PartialEq)]
218 pub enum PaymentFailReason {
219         /// Indicate the preimage for payment_hash is not known after a PaymentReceived event
220         PreimageUnknown,
221         /// Indicate the payment amount is incorrect ( received is < expected or > 2*expected ) after a PaymentReceived event
222         AmountMismatch,
223 }
224
225 /// We hold back HTLCs we intend to relay for a random interval in the range (this, 5*this). This
226 /// provides some limited amount of privacy. Ideally this would range from somewhere like 1 second
227 /// to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly. We could
228 /// probably increase this significantly.
229 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
230
231 struct HTLCForwardInfo {
232         prev_short_channel_id: u64,
233         prev_htlc_id: u64,
234         forward_info: PendingForwardHTLCInfo,
235 }
236
237 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
238 /// be sent in the order they appear in the return value, however sometimes the order needs to be
239 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
240 /// they were originally sent). In those cases, this enum is also returned.
241 #[derive(Clone, PartialEq)]
242 pub(super) enum RAACommitmentOrder {
243         /// Send the CommitmentUpdate messages first
244         CommitmentFirst,
245         /// Send the RevokeAndACK message first
246         RevokeAndACKFirst,
247 }
248
249 struct ChannelHolder {
250         by_id: HashMap<[u8; 32], Channel>,
251         short_to_id: HashMap<u64, [u8; 32]>,
252         next_forward: Instant,
253         /// short channel id -> forward infos. Key of 0 means payments received
254         /// Note that while this is held in the same mutex as the channels themselves, no consistency
255         /// guarantees are made about there existing a channel with the short id here, nor the short
256         /// ids in the PendingForwardHTLCInfo!
257         forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
258         /// Note that while this is held in the same mutex as the channels themselves, no consistency
259         /// guarantees are made about the channels given here actually existing anymore by the time you
260         /// go to read them!
261         claimable_htlcs: HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
262         /// Messages to send to peers - pushed to in the same lock that they are generated in (except
263         /// for broadcast messages, where ordering isn't as strict).
264         pending_msg_events: Vec<events::MessageSendEvent>,
265 }
266 struct MutChannelHolder<'a> {
267         by_id: &'a mut HashMap<[u8; 32], Channel>,
268         short_to_id: &'a mut HashMap<u64, [u8; 32]>,
269         next_forward: &'a mut Instant,
270         forward_htlcs: &'a mut HashMap<u64, Vec<HTLCForwardInfo>>,
271         claimable_htlcs: &'a mut HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
272         pending_msg_events: &'a mut Vec<events::MessageSendEvent>,
273 }
274 impl ChannelHolder {
275         fn borrow_parts(&mut self) -> MutChannelHolder {
276                 MutChannelHolder {
277                         by_id: &mut self.by_id,
278                         short_to_id: &mut self.short_to_id,
279                         next_forward: &mut self.next_forward,
280                         forward_htlcs: &mut self.forward_htlcs,
281                         claimable_htlcs: &mut self.claimable_htlcs,
282                         pending_msg_events: &mut self.pending_msg_events,
283                 }
284         }
285 }
286
287 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
288 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
289
290 /// Manager which keeps track of a number of channels and sends messages to the appropriate
291 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
292 ///
293 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
294 /// to individual Channels.
295 ///
296 /// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
297 /// all peers during write/read (though does not modify this instance, only the instance being
298 /// serialized). This will result in any channels which have not yet exchanged funding_created (ie
299 /// called funding_transaction_generated for outbound channels).
300 ///
301 /// Note that you can be a bit lazier about writing out ChannelManager than you can be with
302 /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
303 /// returning from ManyChannelMonitor::add_update_monitor, with ChannelManagers, writing updates
304 /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during
305 /// the serialization process). If the deserialized version is out-of-date compared to the
306 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
307 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
308 ///
309 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelManager), which
310 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
311 /// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
312 /// block_connected() to step towards your best block) upon deserialization before using the
313 /// object!
314 pub struct ChannelManager {
315         default_configuration: UserConfig,
316         genesis_hash: Sha256dHash,
317         fee_estimator: Arc<FeeEstimator>,
318         monitor: Arc<ManyChannelMonitor>,
319         chain_monitor: Arc<ChainWatchInterface>,
320         tx_broadcaster: Arc<BroadcasterInterface>,
321
322         latest_block_height: AtomicUsize,
323         last_block_hash: Mutex<Sha256dHash>,
324         secp_ctx: Secp256k1<secp256k1::All>,
325
326         channel_state: Mutex<ChannelHolder>,
327         our_network_key: SecretKey,
328
329         pending_events: Mutex<Vec<events::Event>>,
330         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
331         /// Essentially just when we're serializing ourselves out.
332         /// Taken first everywhere where we are making changes before any other locks.
333         total_consistency_lock: RwLock<()>,
334
335         keys_manager: Arc<KeysInterface>,
336
337         logger: Arc<Logger>,
338 }
339
340 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
341 /// HTLC's CLTV. This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
342 /// ie the node we forwarded the payment on to should always have enough room to reliably time out
343 /// the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
344 /// CLTV_CLAIM_BUFFER point (we static assert that its at least 3 blocks more).
345 const CLTV_EXPIRY_DELTA: u16 = 6 * 12; //TODO?
346 const CLTV_FAR_FAR_AWAY: u32 = 6 * 24 * 7; //TODO?
347
348 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + 2*HTLC_FAIL_TIMEOUT_BLOCKS +
349 // HTLC_FAIL_ANTI_REORG_DELAY, ie that if the next-hop peer fails the HTLC within
350 // HTLC_FAIL_TIMEOUT_BLOCKS then we'll still have HTLC_FAIL_TIMEOUT_BLOCKS left to fail it
351 // backwards ourselves before hitting the CLTV_CLAIM_BUFFER point and failing the channel
352 // on-chain to time out the HTLC.
353 #[deny(const_err)]
354 #[allow(dead_code)]
355 const CHECK_CLTV_EXPIRY_SANITY: u32 = CLTV_EXPIRY_DELTA as u32 - 2*HTLC_FAIL_TIMEOUT_BLOCKS - CLTV_CLAIM_BUFFER - HTLC_FAIL_ANTI_REORG_DELAY;
356
357 // Check for ability of an attacker to make us fail on-chain by delaying inbound claim. See
358 // ChannelMontior::would_broadcast_at_height for a description of why this is needed.
359 #[deny(const_err)]
360 #[allow(dead_code)]
361 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = CLTV_EXPIRY_DELTA as u32 - HTLC_FAIL_TIMEOUT_BLOCKS - 2*CLTV_CLAIM_BUFFER;
362
363 macro_rules! secp_call {
364         ( $res: expr, $err: expr ) => {
365                 match $res {
366                         Ok(key) => key,
367                         Err(_) => return Err($err),
368                 }
369         };
370 }
371
372 struct OnionKeys {
373         #[cfg(test)]
374         shared_secret: SharedSecret,
375         #[cfg(test)]
376         blinding_factor: [u8; 32],
377         ephemeral_pubkey: PublicKey,
378         rho: [u8; 32],
379         mu: [u8; 32],
380 }
381
382 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
383 pub struct ChannelDetails {
384         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
385         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
386         /// Note that this means this value is *not* persistent - it can change once during the
387         /// lifetime of the channel.
388         pub channel_id: [u8; 32],
389         /// The position of the funding transaction in the chain. None if the funding transaction has
390         /// not yet been confirmed and the channel fully opened.
391         pub short_channel_id: Option<u64>,
392         /// The node_id of our counterparty
393         pub remote_network_id: PublicKey,
394         /// The value, in satoshis, of this channel as appears in the funding output
395         pub channel_value_satoshis: u64,
396         /// The user_id passed in to create_channel, or 0 if the channel was inbound.
397         pub user_id: u64,
398 }
399
400 macro_rules! handle_error {
401         ($self: ident, $internal: expr, $their_node_id: expr) => {
402                 match $internal {
403                         Ok(msg) => Ok(msg),
404                         Err(MsgHandleErrInternal { err, shutdown_finish }) => {
405                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
406                                         $self.finish_force_close_channel(shutdown_res);
407                                         if let Some(update) = update_option {
408                                                 let mut channel_state = $self.channel_state.lock().unwrap();
409                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
410                                                         msg: update
411                                                 });
412                                         }
413                                 }
414                                 Err(err)
415                         },
416                 }
417         }
418 }
419
420 macro_rules! break_chan_entry {
421         ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
422                 match $res {
423                         Ok(res) => res,
424                         Err(ChannelError::Ignore(msg)) => {
425                                 break Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
426                         },
427                         Err(ChannelError::Close(msg)) => {
428                                 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
429                                 let (channel_id, mut chan) = $entry.remove_entry();
430                                 if let Some(short_id) = chan.get_short_channel_id() {
431                                         $channel_state.short_to_id.remove(&short_id);
432                                 }
433                                 break Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
434                         },
435                 }
436         }
437 }
438
439 macro_rules! try_chan_entry {
440         ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
441                 match $res {
442                         Ok(res) => res,
443                         Err(ChannelError::Ignore(msg)) => {
444                                 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
445                         },
446                         Err(ChannelError::Close(msg)) => {
447                                 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
448                                 let (channel_id, mut chan) = $entry.remove_entry();
449                                 if let Some(short_id) = chan.get_short_channel_id() {
450                                         $channel_state.short_to_id.remove(&short_id);
451                                 }
452                                 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
453                         },
454                 }
455         }
456 }
457
458 macro_rules! return_monitor_err {
459         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
460                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new())
461         };
462         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $raa_first_dropped_cs: expr) => {
463                 if $action_type != RAACommitmentOrder::RevokeAndACKFirst { panic!("Bad return_monitor_err call!"); }
464                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new(), $raa_first_dropped_cs)
465         };
466         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr) => {
467                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, $failed_forwards, $failed_fails, false)
468         };
469         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr, $raa_first_dropped_cs: expr) => {
470                 match $err {
471                         ChannelMonitorUpdateErr::PermanentFailure => {
472                                 let (channel_id, mut chan) = $entry.remove_entry();
473                                 if let Some(short_id) = chan.get_short_channel_id() {
474                                         $channel_state.short_to_id.remove(&short_id);
475                                 }
476                                 // TODO: $failed_fails is dropped here, which will cause other channels to hit the
477                                 // chain in a confused state! We need to move them into the ChannelMonitor which
478                                 // will be responsible for failing backwards once things confirm on-chain.
479                                 // It's ok that we drop $failed_forwards here - at this point we'd rather they
480                                 // broadcast HTLC-Timeout and pay the associated fees to get their funds back than
481                                 // us bother trying to claim it just to forward on to another peer. If we're
482                                 // splitting hairs we'd prefer to claim payments that were to us, but we haven't
483                                 // given up the preimage yet, so might as well just wait until the payment is
484                                 // retried, avoiding the on-chain fees.
485                                 return Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
486                         },
487                         ChannelMonitorUpdateErr::TemporaryFailure => {
488                                 $entry.get_mut().monitor_update_failed($action_type, $failed_forwards, $failed_fails, $raa_first_dropped_cs);
489                                 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore("Failed to update ChannelMonitor"), *$entry.key()));
490                         },
491                 }
492         }
493 }
494
495 // Does not break in case of TemporaryFailure!
496 macro_rules! maybe_break_monitor_err {
497         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
498                 match $err {
499                         ChannelMonitorUpdateErr::PermanentFailure => {
500                                 let (channel_id, mut chan) = $entry.remove_entry();
501                                 if let Some(short_id) = chan.get_short_channel_id() {
502                                         $channel_state.short_to_id.remove(&short_id);
503                                 }
504                                 break Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
505                         },
506                         ChannelMonitorUpdateErr::TemporaryFailure => {
507                                 $entry.get_mut().monitor_update_failed($action_type, Vec::new(), Vec::new(), false);
508                         },
509                 }
510         }
511 }
512
513 impl ChannelManager {
514         /// Constructs a new ChannelManager to hold several channels and route between them.
515         ///
516         /// This is the main "logic hub" for all channel-related actions, and implements
517         /// ChannelMessageHandler.
518         ///
519         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
520         ///
521         /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
522         pub fn new(network: Network, feeest: Arc<FeeEstimator>, monitor: Arc<ManyChannelMonitor>, chain_monitor: Arc<ChainWatchInterface>, tx_broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>,keys_manager: Arc<KeysInterface>, config: UserConfig) -> Result<Arc<ChannelManager>, secp256k1::Error> {
523                 let secp_ctx = Secp256k1::new();
524
525                 let res = Arc::new(ChannelManager {
526                         default_configuration: config.clone(),
527                         genesis_hash: genesis_block(network).header.bitcoin_hash(),
528                         fee_estimator: feeest.clone(),
529                         monitor: monitor.clone(),
530                         chain_monitor,
531                         tx_broadcaster,
532
533                         latest_block_height: AtomicUsize::new(0), //TODO: Get an init value
534                         last_block_hash: Mutex::new(Default::default()),
535                         secp_ctx,
536
537                         channel_state: Mutex::new(ChannelHolder{
538                                 by_id: HashMap::new(),
539                                 short_to_id: HashMap::new(),
540                                 next_forward: Instant::now(),
541                                 forward_htlcs: HashMap::new(),
542                                 claimable_htlcs: HashMap::new(),
543                                 pending_msg_events: Vec::new(),
544                         }),
545                         our_network_key: keys_manager.get_node_secret(),
546
547                         pending_events: Mutex::new(Vec::new()),
548                         total_consistency_lock: RwLock::new(()),
549
550                         keys_manager,
551
552                         logger,
553                 });
554                 let weak_res = Arc::downgrade(&res);
555                 res.chain_monitor.register_listener(weak_res);
556                 Ok(res)
557         }
558
559         /// Creates a new outbound channel to the given remote node and with the given value.
560         ///
561         /// user_id will be provided back as user_channel_id in FundingGenerationReady and
562         /// FundingBroadcastSafe events to allow tracking of which events correspond with which
563         /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
564         /// may wish to avoid using 0 for user_id here.
565         ///
566         /// If successful, will generate a SendOpenChannel message event, so you should probably poll
567         /// PeerManager::process_events afterwards.
568         ///
569         /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
570         /// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
571         pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64) -> Result<(), APIError> {
572                 if channel_value_satoshis < 1000 {
573                         return Err(APIError::APIMisuseError { err: "channel_value must be at least 1000 satoshis" });
574                 }
575
576                 let channel = Channel::new_outbound(&*self.fee_estimator, &self.keys_manager, their_network_key, channel_value_satoshis, push_msat, user_id, Arc::clone(&self.logger), &self.default_configuration)?;
577                 let res = channel.get_open_channel(self.genesis_hash.clone(), &*self.fee_estimator);
578
579                 let _ = self.total_consistency_lock.read().unwrap();
580                 let mut channel_state = self.channel_state.lock().unwrap();
581                 match channel_state.by_id.entry(channel.channel_id()) {
582                         hash_map::Entry::Occupied(_) => {
583                                 if cfg!(feature = "fuzztarget") {
584                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG" });
585                                 } else {
586                                         panic!("RNG is bad???");
587                                 }
588                         },
589                         hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
590                 }
591                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
592                         node_id: their_network_key,
593                         msg: res,
594                 });
595                 Ok(())
596         }
597
598         /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
599         /// more information.
600         pub fn list_channels(&self) -> Vec<ChannelDetails> {
601                 let channel_state = self.channel_state.lock().unwrap();
602                 let mut res = Vec::with_capacity(channel_state.by_id.len());
603                 for (channel_id, channel) in channel_state.by_id.iter() {
604                         res.push(ChannelDetails {
605                                 channel_id: (*channel_id).clone(),
606                                 short_channel_id: channel.get_short_channel_id(),
607                                 remote_network_id: channel.get_their_node_id(),
608                                 channel_value_satoshis: channel.get_value_satoshis(),
609                                 user_id: channel.get_user_id(),
610                         });
611                 }
612                 res
613         }
614
615         /// Gets the list of usable channels, in random order. Useful as an argument to
616         /// Router::get_route to ensure non-announced channels are used.
617         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
618                 let channel_state = self.channel_state.lock().unwrap();
619                 let mut res = Vec::with_capacity(channel_state.by_id.len());
620                 for (channel_id, channel) in channel_state.by_id.iter() {
621                         // Note we use is_live here instead of usable which leads to somewhat confused
622                         // internal/external nomenclature, but that's ok cause that's probably what the user
623                         // really wanted anyway.
624                         if channel.is_live() {
625                                 res.push(ChannelDetails {
626                                         channel_id: (*channel_id).clone(),
627                                         short_channel_id: channel.get_short_channel_id(),
628                                         remote_network_id: channel.get_their_node_id(),
629                                         channel_value_satoshis: channel.get_value_satoshis(),
630                                         user_id: channel.get_user_id(),
631                                 });
632                         }
633                 }
634                 res
635         }
636
637         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
638         /// will be accepted on the given channel, and after additional timeout/the closing of all
639         /// pending HTLCs, the channel will be closed on chain.
640         ///
641         /// May generate a SendShutdown message event on success, which should be relayed.
642         pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
643                 let _ = self.total_consistency_lock.read().unwrap();
644
645                 let (mut failed_htlcs, chan_option) = {
646                         let mut channel_state_lock = self.channel_state.lock().unwrap();
647                         let channel_state = channel_state_lock.borrow_parts();
648                         match channel_state.by_id.entry(channel_id.clone()) {
649                                 hash_map::Entry::Occupied(mut chan_entry) => {
650                                         let (shutdown_msg, failed_htlcs) = chan_entry.get_mut().get_shutdown()?;
651                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
652                                                 node_id: chan_entry.get().get_their_node_id(),
653                                                 msg: shutdown_msg
654                                         });
655                                         if chan_entry.get().is_shutdown() {
656                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
657                                                         channel_state.short_to_id.remove(&short_id);
658                                                 }
659                                                 (failed_htlcs, Some(chan_entry.remove_entry().1))
660                                         } else { (failed_htlcs, None) }
661                                 },
662                                 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: "No such channel"})
663                         }
664                 };
665                 for htlc_source in failed_htlcs.drain(..) {
666                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
667                 }
668                 let chan_update = if let Some(chan) = chan_option {
669                         if let Ok(update) = self.get_channel_update(&chan) {
670                                 Some(update)
671                         } else { None }
672                 } else { None };
673
674                 if let Some(update) = chan_update {
675                         let mut channel_state = self.channel_state.lock().unwrap();
676                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
677                                 msg: update
678                         });
679                 }
680
681                 Ok(())
682         }
683
684         #[inline]
685         fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
686                 let (local_txn, mut failed_htlcs) = shutdown_res;
687                 log_trace!(self, "Finishing force-closure of channel with {} transactions to broadcast and {} HTLCs to fail", local_txn.len(), failed_htlcs.len());
688                 for htlc_source in failed_htlcs.drain(..) {
689                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
690                 }
691                 for tx in local_txn {
692                         self.tx_broadcaster.broadcast_transaction(&tx);
693                 }
694         }
695
696         /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
697         /// the chain and rejecting new HTLCs on the given channel.
698         pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
699                 let _ = self.total_consistency_lock.read().unwrap();
700
701                 let mut chan = {
702                         let mut channel_state_lock = self.channel_state.lock().unwrap();
703                         let channel_state = channel_state_lock.borrow_parts();
704                         if let Some(chan) = channel_state.by_id.remove(channel_id) {
705                                 if let Some(short_id) = chan.get_short_channel_id() {
706                                         channel_state.short_to_id.remove(&short_id);
707                                 }
708                                 chan
709                         } else {
710                                 return;
711                         }
712                 };
713                 log_trace!(self, "Force-closing channel {}", log_bytes!(channel_id[..]));
714                 self.finish_force_close_channel(chan.force_shutdown());
715                 if let Ok(update) = self.get_channel_update(&chan) {
716                         let mut channel_state = self.channel_state.lock().unwrap();
717                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
718                                 msg: update
719                         });
720                 }
721         }
722
723         /// Force close all channels, immediately broadcasting the latest local commitment transaction
724         /// for each to the chain and rejecting new HTLCs on each.
725         pub fn force_close_all_channels(&self) {
726                 for chan in self.list_channels() {
727                         self.force_close_channel(&chan.channel_id);
728                 }
729         }
730
731         #[inline]
732         fn gen_rho_mu_from_shared_secret(shared_secret: &[u8]) -> ([u8; 32], [u8; 32]) {
733                 assert_eq!(shared_secret.len(), 32);
734                 ({
735                         let mut hmac = Hmac::new(Sha256::new(), &[0x72, 0x68, 0x6f]); // rho
736                         hmac.input(&shared_secret[..]);
737                         let mut res = [0; 32];
738                         hmac.raw_result(&mut res);
739                         res
740                 },
741                 {
742                         let mut hmac = Hmac::new(Sha256::new(), &[0x6d, 0x75]); // mu
743                         hmac.input(&shared_secret[..]);
744                         let mut res = [0; 32];
745                         hmac.raw_result(&mut res);
746                         res
747                 })
748         }
749
750         #[inline]
751         fn gen_um_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
752                 assert_eq!(shared_secret.len(), 32);
753                 let mut hmac = Hmac::new(Sha256::new(), &[0x75, 0x6d]); // um
754                 hmac.input(&shared_secret[..]);
755                 let mut res = [0; 32];
756                 hmac.raw_result(&mut res);
757                 res
758         }
759
760         #[inline]
761         fn gen_ammag_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
762                 assert_eq!(shared_secret.len(), 32);
763                 let mut hmac = Hmac::new(Sha256::new(), &[0x61, 0x6d, 0x6d, 0x61, 0x67]); // ammag
764                 hmac.input(&shared_secret[..]);
765                 let mut res = [0; 32];
766                 hmac.raw_result(&mut res);
767                 res
768         }
769
770         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
771         #[inline]
772         fn construct_onion_keys_callback<T: secp256k1::Signing, FType: FnMut(SharedSecret, [u8; 32], PublicKey, &RouteHop)> (secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey, mut callback: FType) -> Result<(), secp256k1::Error> {
773                 let mut blinded_priv = session_priv.clone();
774                 let mut blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
775
776                 for hop in route.hops.iter() {
777                         let shared_secret = SharedSecret::new(secp_ctx, &hop.pubkey, &blinded_priv);
778
779                         let mut sha = Sha256::new();
780                         sha.input(&blinded_pub.serialize()[..]);
781                         sha.input(&shared_secret[..]);
782                         let mut blinding_factor = [0u8; 32];
783                         sha.result(&mut blinding_factor);
784
785                         let ephemeral_pubkey = blinded_pub;
786
787                         blinded_priv.mul_assign(secp_ctx, &SecretKey::from_slice(secp_ctx, &blinding_factor)?)?;
788                         blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
789
790                         callback(shared_secret, blinding_factor, ephemeral_pubkey, hop);
791                 }
792
793                 Ok(())
794         }
795
796         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
797         fn construct_onion_keys<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey) -> Result<Vec<OnionKeys>, secp256k1::Error> {
798                 let mut res = Vec::with_capacity(route.hops.len());
799
800                 Self::construct_onion_keys_callback(secp_ctx, route, session_priv, |shared_secret, _blinding_factor, ephemeral_pubkey, _| {
801                         let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret[..]);
802
803                         res.push(OnionKeys {
804                                 #[cfg(test)]
805                                 shared_secret,
806                                 #[cfg(test)]
807                                 blinding_factor: _blinding_factor,
808                                 ephemeral_pubkey,
809                                 rho,
810                                 mu,
811                         });
812                 })?;
813
814                 Ok(res)
815         }
816
817         /// returns the hop data, as well as the first-hop value_msat and CLTV value we should send.
818         fn build_onion_payloads(route: &Route, starting_htlc_offset: u32) -> Result<(Vec<msgs::OnionHopData>, u64, u32), APIError> {
819                 let mut cur_value_msat = 0u64;
820                 let mut cur_cltv = starting_htlc_offset;
821                 let mut last_short_channel_id = 0;
822                 let mut res: Vec<msgs::OnionHopData> = Vec::with_capacity(route.hops.len());
823                 internal_traits::test_no_dealloc::<msgs::OnionHopData>(None);
824                 unsafe { res.set_len(route.hops.len()); }
825
826                 for (idx, hop) in route.hops.iter().enumerate().rev() {
827                         // First hop gets special values so that it can check, on receipt, that everything is
828                         // exactly as it should be (and the next hop isn't trying to probe to find out if we're
829                         // the intended recipient).
830                         let value_msat = if cur_value_msat == 0 { hop.fee_msat } else { cur_value_msat };
831                         let cltv = if cur_cltv == starting_htlc_offset { hop.cltv_expiry_delta + starting_htlc_offset } else { cur_cltv };
832                         res[idx] = msgs::OnionHopData {
833                                 realm: 0,
834                                 data: msgs::OnionRealm0HopData {
835                                         short_channel_id: last_short_channel_id,
836                                         amt_to_forward: value_msat,
837                                         outgoing_cltv_value: cltv,
838                                 },
839                                 hmac: [0; 32],
840                         };
841                         cur_value_msat += hop.fee_msat;
842                         if cur_value_msat >= 21000000 * 100000000 * 1000 {
843                                 return Err(APIError::RouteError{err: "Channel fees overflowed?!"});
844                         }
845                         cur_cltv += hop.cltv_expiry_delta as u32;
846                         if cur_cltv >= 500000000 {
847                                 return Err(APIError::RouteError{err: "Channel CLTV overflowed?!"});
848                         }
849                         last_short_channel_id = hop.short_channel_id;
850                 }
851                 Ok((res, cur_value_msat, cur_cltv))
852         }
853
854         #[inline]
855         fn shift_arr_right(arr: &mut [u8; 20*65]) {
856                 unsafe {
857                         ptr::copy(arr[0..].as_ptr(), arr[65..].as_mut_ptr(), 19*65);
858                 }
859                 for i in 0..65 {
860                         arr[i] = 0;
861                 }
862         }
863
864         #[inline]
865         fn xor_bufs(dst: &mut[u8], src: &[u8]) {
866                 assert_eq!(dst.len(), src.len());
867
868                 for i in 0..dst.len() {
869                         dst[i] ^= src[i];
870                 }
871         }
872
873         const ZERO:[u8; 21*65] = [0; 21*65];
874         fn construct_onion_packet(mut payloads: Vec<msgs::OnionHopData>, onion_keys: Vec<OnionKeys>, associated_data: &PaymentHash) -> msgs::OnionPacket {
875                 let mut buf = Vec::with_capacity(21*65);
876                 buf.resize(21*65, 0);
877
878                 let filler = {
879                         let iters = payloads.len() - 1;
880                         let end_len = iters * 65;
881                         let mut res = Vec::with_capacity(end_len);
882                         res.resize(end_len, 0);
883
884                         for (i, keys) in onion_keys.iter().enumerate() {
885                                 if i == payloads.len() - 1 { continue; }
886                                 let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
887                                 chacha.process(&ChannelManager::ZERO, &mut buf); // We don't have a seek function :(
888                                 ChannelManager::xor_bufs(&mut res[0..(i + 1)*65], &buf[(20 - i)*65..21*65]);
889                         }
890                         res
891                 };
892
893                 let mut packet_data = [0; 20*65];
894                 let mut hmac_res = [0; 32];
895
896                 for (i, (payload, keys)) in payloads.iter_mut().zip(onion_keys.iter()).rev().enumerate() {
897                         ChannelManager::shift_arr_right(&mut packet_data);
898                         payload.hmac = hmac_res;
899                         packet_data[0..65].copy_from_slice(&payload.encode()[..]);
900
901                         let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
902                         chacha.process(&packet_data, &mut buf[0..20*65]);
903                         packet_data[..].copy_from_slice(&buf[0..20*65]);
904
905                         if i == 0 {
906                                 packet_data[20*65 - filler.len()..20*65].copy_from_slice(&filler[..]);
907                         }
908
909                         let mut hmac = Hmac::new(Sha256::new(), &keys.mu);
910                         hmac.input(&packet_data);
911                         hmac.input(&associated_data.0[..]);
912                         hmac.raw_result(&mut hmac_res);
913                 }
914
915                 msgs::OnionPacket{
916                         version: 0,
917                         public_key: Ok(onion_keys.first().unwrap().ephemeral_pubkey),
918                         hop_data: packet_data,
919                         hmac: hmac_res,
920                 }
921         }
922
923         /// Encrypts a failure packet. raw_packet can either be a
924         /// msgs::DecodedOnionErrorPacket.encode() result or a msgs::OnionErrorPacket.data element.
925         fn encrypt_failure_packet(shared_secret: &[u8], raw_packet: &[u8]) -> msgs::OnionErrorPacket {
926                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
927
928                 let mut packet_crypted = Vec::with_capacity(raw_packet.len());
929                 packet_crypted.resize(raw_packet.len(), 0);
930                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
931                 chacha.process(&raw_packet, &mut packet_crypted[..]);
932                 msgs::OnionErrorPacket {
933                         data: packet_crypted,
934                 }
935         }
936
937         fn build_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::DecodedOnionErrorPacket {
938                 assert_eq!(shared_secret.len(), 32);
939                 assert!(failure_data.len() <= 256 - 2);
940
941                 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
942
943                 let failuremsg = {
944                         let mut res = Vec::with_capacity(2 + failure_data.len());
945                         res.push(((failure_type >> 8) & 0xff) as u8);
946                         res.push(((failure_type >> 0) & 0xff) as u8);
947                         res.extend_from_slice(&failure_data[..]);
948                         res
949                 };
950                 let pad = {
951                         let mut res = Vec::with_capacity(256 - 2 - failure_data.len());
952                         res.resize(256 - 2 - failure_data.len(), 0);
953                         res
954                 };
955                 let mut packet = msgs::DecodedOnionErrorPacket {
956                         hmac: [0; 32],
957                         failuremsg: failuremsg,
958                         pad: pad,
959                 };
960
961                 let mut hmac = Hmac::new(Sha256::new(), &um);
962                 hmac.input(&packet.encode()[32..]);
963                 hmac.raw_result(&mut packet.hmac);
964
965                 packet
966         }
967
968         #[inline]
969         fn build_first_hop_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::OnionErrorPacket {
970                 let failure_packet = ChannelManager::build_failure_packet(shared_secret, failure_type, failure_data);
971                 ChannelManager::encrypt_failure_packet(shared_secret, &failure_packet.encode()[..])
972         }
973
974         fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder>) {
975                 macro_rules! get_onion_hash {
976                         () => {
977                                 {
978                                         let mut sha = Sha256::new();
979                                         sha.input(&msg.onion_routing_packet.hop_data);
980                                         let mut onion_hash = [0; 32];
981                                         sha.result(&mut onion_hash);
982                                         onion_hash
983                                 }
984                         }
985                 }
986
987                 if let Err(_) = msg.onion_routing_packet.public_key {
988                         log_info!(self, "Failed to accept/forward incoming HTLC with invalid ephemeral pubkey");
989                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
990                                 channel_id: msg.channel_id,
991                                 htlc_id: msg.htlc_id,
992                                 sha256_of_onion: get_onion_hash!(),
993                                 failure_code: 0x8000 | 0x4000 | 6,
994                         })), self.channel_state.lock().unwrap());
995                 }
996
997                 let shared_secret = {
998                         let mut arr = [0; 32];
999                         arr.copy_from_slice(&SharedSecret::new(&self.secp_ctx, &msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key)[..]);
1000                         arr
1001                 };
1002                 let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
1003
1004                 let mut channel_state = None;
1005                 macro_rules! return_err {
1006                         ($msg: expr, $err_code: expr, $data: expr) => {
1007                                 {
1008                                         log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
1009                                         if channel_state.is_none() {
1010                                                 channel_state = Some(self.channel_state.lock().unwrap());
1011                                         }
1012                                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
1013                                                 channel_id: msg.channel_id,
1014                                                 htlc_id: msg.htlc_id,
1015                                                 reason: ChannelManager::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
1016                                         })), channel_state.unwrap());
1017                                 }
1018                         }
1019                 }
1020
1021                 if msg.onion_routing_packet.version != 0 {
1022                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
1023                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
1024                         //the hash doesn't really serve any purpuse - in the case of hashing all data, the
1025                         //receiving node would have to brute force to figure out which version was put in the
1026                         //packet by the node that send us the message, in the case of hashing the hop_data, the
1027                         //node knows the HMAC matched, so they already know what is there...
1028                         return_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4, &get_onion_hash!());
1029                 }
1030
1031                 let mut hmac = Hmac::new(Sha256::new(), &mu);
1032                 hmac.input(&msg.onion_routing_packet.hop_data);
1033                 hmac.input(&msg.payment_hash.0[..]);
1034                 if hmac.result() != MacResult::new(&msg.onion_routing_packet.hmac) {
1035                         return_err!("HMAC Check failed", 0x8000 | 0x4000 | 5, &get_onion_hash!());
1036                 }
1037
1038                 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
1039                 let next_hop_data = {
1040                         let mut decoded = [0; 65];
1041                         chacha.process(&msg.onion_routing_packet.hop_data[0..65], &mut decoded);
1042                         match msgs::OnionHopData::read(&mut Cursor::new(&decoded[..])) {
1043                                 Err(err) => {
1044                                         let error_code = match err {
1045                                                 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
1046                                                 _ => 0x2000 | 2, // Should never happen
1047                                         };
1048                                         return_err!("Unable to decode our hop data", error_code, &[0;0]);
1049                                 },
1050                                 Ok(msg) => msg
1051                         }
1052                 };
1053
1054                 let pending_forward_info = if next_hop_data.hmac == [0; 32] {
1055                                 // OUR PAYMENT!
1056                                 // final_expiry_too_soon
1057                                 if (msg.cltv_expiry as u64) < self.latest_block_height.load(Ordering::Acquire) as u64 + (CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS) as u64 {
1058                                         return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
1059                                 }
1060                                 // final_incorrect_htlc_amount
1061                                 if next_hop_data.data.amt_to_forward > msg.amount_msat {
1062                                         return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
1063                                 }
1064                                 // final_incorrect_cltv_expiry
1065                                 if next_hop_data.data.outgoing_cltv_value != msg.cltv_expiry {
1066                                         return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
1067                                 }
1068
1069                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
1070                                 // message, however that would leak that we are the recipient of this payment, so
1071                                 // instead we stay symmetric with the forwarding case, only responding (after a
1072                                 // delay) once they've send us a commitment_signed!
1073
1074                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1075                                         onion_packet: None,
1076                                         payment_hash: msg.payment_hash.clone(),
1077                                         short_channel_id: 0,
1078                                         incoming_shared_secret: shared_secret,
1079                                         amt_to_forward: next_hop_data.data.amt_to_forward,
1080                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1081                                 })
1082                         } else {
1083                                 let mut new_packet_data = [0; 20*65];
1084                                 chacha.process(&msg.onion_routing_packet.hop_data[65..], &mut new_packet_data[0..19*65]);
1085                                 chacha.process(&ChannelManager::ZERO[0..65], &mut new_packet_data[19*65..]);
1086
1087                                 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
1088
1089                                 let blinding_factor = {
1090                                         let mut sha = Sha256::new();
1091                                         sha.input(&new_pubkey.serialize()[..]);
1092                                         sha.input(&shared_secret);
1093                                         let mut res = [0u8; 32];
1094                                         sha.result(&mut res);
1095                                         match SecretKey::from_slice(&self.secp_ctx, &res) {
1096                                                 Err(_) => {
1097                                                         return_err!("Blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
1098                                                 },
1099                                                 Ok(key) => key
1100                                         }
1101                                 };
1102
1103                                 if let Err(_) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor) {
1104                                         return_err!("New blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
1105                                 }
1106
1107                                 let outgoing_packet = msgs::OnionPacket {
1108                                         version: 0,
1109                                         public_key: Ok(new_pubkey),
1110                                         hop_data: new_packet_data,
1111                                         hmac: next_hop_data.hmac.clone(),
1112                                 };
1113
1114                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1115                                         onion_packet: Some(outgoing_packet),
1116                                         payment_hash: msg.payment_hash.clone(),
1117                                         short_channel_id: next_hop_data.data.short_channel_id,
1118                                         incoming_shared_secret: shared_secret,
1119                                         amt_to_forward: next_hop_data.data.amt_to_forward,
1120                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1121                                 })
1122                         };
1123
1124                 channel_state = Some(self.channel_state.lock().unwrap());
1125                 if let &PendingHTLCStatus::Forward(PendingForwardHTLCInfo { ref onion_packet, ref short_channel_id, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
1126                         if onion_packet.is_some() { // If short_channel_id is 0 here, we'll reject them in the body here
1127                                 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
1128                                 let forwarding_id = match id_option {
1129                                         None => { // unknown_next_peer
1130                                                 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
1131                                         },
1132                                         Some(id) => id.clone(),
1133                                 };
1134                                 if let Some((err, code, chan_update)) = loop {
1135                                         let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
1136
1137                                         // Note that we could technically not return an error yet here and just hope
1138                                         // that the connection is reestablished or monitor updated by the time we get
1139                                         // around to doing the actual forward, but better to fail early if we can and
1140                                         // hopefully an attacker trying to path-trace payments cannot make this occur
1141                                         // on a small/per-node/per-channel scale.
1142                                         if !chan.is_live() { // channel_disabled
1143                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
1144                                         }
1145                                         if *amt_to_forward < chan.get_their_htlc_minimum_msat() { // amount_below_minimum
1146                                                 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
1147                                         }
1148                                         let fee = amt_to_forward.checked_mul(chan.get_fee_proportional_millionths() as u64).and_then(|prop_fee| { (prop_fee / 1000000).checked_add(chan.get_our_fee_base_msat(&*self.fee_estimator) as u64) });
1149                                         if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
1150                                                 break Some(("Prior hop has deviated from specified fees parameters or origin node has obsolete ones", 0x1000 | 12, Some(self.get_channel_update(chan).unwrap())));
1151                                         }
1152                                         if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 { // incorrect_cltv_expiry
1153                                                 break Some(("Forwarding node has tampered with the intended HTLC values or origin node has an obsolete cltv_expiry_delta", 0x1000 | 13, Some(self.get_channel_update(chan).unwrap())));
1154                                         }
1155                                         let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1156                                         // We want to have at least HTLC_FAIL_TIMEOUT_BLOCKS to fail prior to going on chain CLAIM_BUFFER blocks before expiration
1157                                         if msg.cltv_expiry <= cur_height + CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS as u32 { // expiry_too_soon
1158                                                 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1159                                         }
1160                                         if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
1161                                                 break Some(("CLTV expiry is too far in the future", 21, None));
1162                                         }
1163                                         break None;
1164                                 }
1165                                 {
1166                                         let mut res = Vec::with_capacity(8 + 128);
1167                                         if let Some(chan_update) = chan_update {
1168                                                 if code == 0x1000 | 11 || code == 0x1000 | 12 {
1169                                                         res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
1170                                                 }
1171                                                 else if code == 0x1000 | 13 {
1172                                                         res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
1173                                                 }
1174                                                 else if code == 0x1000 | 20 {
1175                                                         res.extend_from_slice(&byte_utils::be16_to_array(chan_update.contents.flags));
1176                                                 }
1177                                                 res.extend_from_slice(&chan_update.encode_with_len()[..]);
1178                                         }
1179                                         return_err!(err, code, &res[..]);
1180                                 }
1181                         }
1182                 }
1183
1184                 (pending_forward_info, channel_state.unwrap())
1185         }
1186
1187         /// only fails if the channel does not yet have an assigned short_id
1188         /// May be called with channel_state already locked!
1189         fn get_channel_update(&self, chan: &Channel) -> Result<msgs::ChannelUpdate, HandleError> {
1190                 let short_channel_id = match chan.get_short_channel_id() {
1191                         None => return Err(HandleError{err: "Channel not yet established", action: None}),
1192                         Some(id) => id,
1193                 };
1194
1195                 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_their_node_id().serialize()[..];
1196
1197                 let unsigned = msgs::UnsignedChannelUpdate {
1198                         chain_hash: self.genesis_hash,
1199                         short_channel_id: short_channel_id,
1200                         timestamp: chan.get_channel_update_count(),
1201                         flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
1202                         cltv_expiry_delta: CLTV_EXPIRY_DELTA,
1203                         htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
1204                         fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
1205                         fee_proportional_millionths: chan.get_fee_proportional_millionths(),
1206                         excess_data: Vec::new(),
1207                 };
1208
1209                 let msg_hash = Sha256dHash::from_data(&unsigned.encode()[..]);
1210                 let sig = self.secp_ctx.sign(&Message::from_slice(&msg_hash[..]).unwrap(), &self.our_network_key);
1211
1212                 Ok(msgs::ChannelUpdate {
1213                         signature: sig,
1214                         contents: unsigned
1215                 })
1216         }
1217
1218         /// Sends a payment along a given route.
1219         ///
1220         /// Value parameters are provided via the last hop in route, see documentation for RouteHop
1221         /// fields for more info.
1222         ///
1223         /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
1224         /// payment), we don't do anything to stop you! We always try to ensure that if the provided
1225         /// next hop knows the preimage to payment_hash they can claim an additional amount as
1226         /// specified in the last hop in the route! Thus, you should probably do your own
1227         /// payment_preimage tracking (which you should already be doing as they represent "proof of
1228         /// payment") and prevent double-sends yourself.
1229         ///
1230         /// May generate a SendHTLCs message event on success, which should be relayed.
1231         ///
1232         /// Raises APIError::RoutError when invalid route or forward parameter
1233         /// (cltv_delta, fee, node public key) is specified.
1234         /// Raises APIError::ChannelUnavailable if the next-hop channel is not available for updates
1235         /// (including due to previous monitor update failure or new permanent monitor update failure).
1236         /// Raised APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
1237         /// relevant updates.
1238         ///
1239         /// In case of APIError::RouteError/APIError::ChannelUnavailable, the payment send has failed
1240         /// and you may wish to retry via a different route immediately.
1241         /// In case of APIError::MonitorUpdateFailed, the commitment update has been irrevocably
1242         /// committed on our end and we're just waiting for a monitor update to send it. Do NOT retry
1243         /// the payment via a different route unless you intend to pay twice!
1244         pub fn send_payment(&self, route: Route, payment_hash: PaymentHash) -> Result<(), APIError> {
1245                 if route.hops.len() < 1 || route.hops.len() > 20 {
1246                         return Err(APIError::RouteError{err: "Route didn't go anywhere/had bogus size"});
1247                 }
1248                 let our_node_id = self.get_our_node_id();
1249                 for (idx, hop) in route.hops.iter().enumerate() {
1250                         if idx != route.hops.len() - 1 && hop.pubkey == our_node_id {
1251                                 return Err(APIError::RouteError{err: "Route went through us but wasn't a simple rebalance loop to us"});
1252                         }
1253                 }
1254
1255                 let session_priv = self.keys_manager.get_session_key();
1256
1257                 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1258
1259                 let onion_keys = secp_call!(ChannelManager::construct_onion_keys(&self.secp_ctx, &route, &session_priv),
1260                                 APIError::RouteError{err: "Pubkey along hop was maliciously selected"});
1261                 let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height)?;
1262                 let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
1263
1264                 let _ = self.total_consistency_lock.read().unwrap();
1265
1266                 let err: Result<(), _> = loop {
1267                         let mut channel_lock = self.channel_state.lock().unwrap();
1268
1269                         let id = match channel_lock.short_to_id.get(&route.hops.first().unwrap().short_channel_id) {
1270                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!"}),
1271                                 Some(id) => id.clone(),
1272                         };
1273
1274                         let channel_state = channel_lock.borrow_parts();
1275                         if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) {
1276                                 match {
1277                                         if chan.get().get_their_node_id() != route.hops.first().unwrap().pubkey {
1278                                                 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1279                                         }
1280                                         if !chan.get().is_live() {
1281                                                 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!"});
1282                                         }
1283                                         break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1284                                                 route: route.clone(),
1285                                                 session_priv: session_priv.clone(),
1286                                                 first_hop_htlc_msat: htlc_msat,
1287                                         }, onion_packet), channel_state, chan)
1288                                 } {
1289                                         Some((update_add, commitment_signed, chan_monitor)) => {
1290                                                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1291                                                         maybe_break_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst);
1292                                                         // Note that MonitorUpdateFailed here indicates (per function docs)
1293                                                         // that we will resent the commitment update once we unfree monitor
1294                                                         // updating, so we have to take special care that we don't return
1295                                                         // something else in case we will resend later!
1296                                                         return Err(APIError::MonitorUpdateFailed);
1297                                                 }
1298
1299                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1300                                                         node_id: route.hops.first().unwrap().pubkey,
1301                                                         updates: msgs::CommitmentUpdate {
1302                                                                 update_add_htlcs: vec![update_add],
1303                                                                 update_fulfill_htlcs: Vec::new(),
1304                                                                 update_fail_htlcs: Vec::new(),
1305                                                                 update_fail_malformed_htlcs: Vec::new(),
1306                                                                 update_fee: None,
1307                                                                 commitment_signed,
1308                                                         },
1309                                                 });
1310                                         },
1311                                         None => {},
1312                                 }
1313                         } else { unreachable!(); }
1314                         return Ok(());
1315                 };
1316
1317                 match handle_error!(self, err, route.hops.first().unwrap().pubkey) {
1318                         Ok(_) => unreachable!(),
1319                         Err(e) => {
1320                                 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
1321                                 } else {
1322                                         log_error!(self, "Got bad keys: {}!", e.err);
1323                                         let mut channel_state = self.channel_state.lock().unwrap();
1324                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1325                                                 node_id: route.hops.first().unwrap().pubkey,
1326                                                 action: e.action,
1327                                         });
1328                                 }
1329                                 Err(APIError::ChannelUnavailable { err: e.err })
1330                         },
1331                 }
1332         }
1333
1334         /// Call this upon creation of a funding transaction for the given channel.
1335         ///
1336         /// Note that ALL inputs in the transaction pointed to by funding_txo MUST spend SegWit outputs
1337         /// or your counterparty can steal your funds!
1338         ///
1339         /// Panics if a funding transaction has already been provided for this channel.
1340         ///
1341         /// May panic if the funding_txo is duplicative with some other channel (note that this should
1342         /// be trivially prevented by using unique funding transaction keys per-channel).
1343         pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1344                 let _ = self.total_consistency_lock.read().unwrap();
1345
1346                 let (chan, msg, chan_monitor) = {
1347                         let (res, chan) = {
1348                                 let mut channel_state = self.channel_state.lock().unwrap();
1349                                 match channel_state.by_id.remove(temporary_channel_id) {
1350                                         Some(mut chan) => {
1351                                                 (chan.get_outbound_funding_created(funding_txo)
1352                                                         .map_err(|e| if let ChannelError::Close(msg) = e {
1353                                                                 MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.force_shutdown(), None)
1354                                                         } else { unreachable!(); })
1355                                                 , chan)
1356                                         },
1357                                         None => return
1358                                 }
1359                         };
1360                         match handle_error!(self, res, chan.get_their_node_id()) {
1361                                 Ok(funding_msg) => {
1362                                         (chan, funding_msg.0, funding_msg.1)
1363                                 },
1364                                 Err(e) => {
1365                                         log_error!(self, "Got bad signatures: {}!", e.err);
1366                                         let mut channel_state = self.channel_state.lock().unwrap();
1367                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1368                                                 node_id: chan.get_their_node_id(),
1369                                                 action: e.action,
1370                                         });
1371                                         return;
1372                                 },
1373                         }
1374                 };
1375                 // Because we have exclusive ownership of the channel here we can release the channel_state
1376                 // lock before add_update_monitor
1377                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1378                         unimplemented!();
1379                 }
1380
1381                 let mut channel_state = self.channel_state.lock().unwrap();
1382                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
1383                         node_id: chan.get_their_node_id(),
1384                         msg: msg,
1385                 });
1386                 match channel_state.by_id.entry(chan.channel_id()) {
1387                         hash_map::Entry::Occupied(_) => {
1388                                 panic!("Generated duplicate funding txid?");
1389                         },
1390                         hash_map::Entry::Vacant(e) => {
1391                                 e.insert(chan);
1392                         }
1393                 }
1394         }
1395
1396         fn get_announcement_sigs(&self, chan: &Channel) -> Option<msgs::AnnouncementSignatures> {
1397                 if !chan.should_announce() { return None }
1398
1399                 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1400                         Ok(res) => res,
1401                         Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1402                 };
1403                 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
1404                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1405
1406                 Some(msgs::AnnouncementSignatures {
1407                         channel_id: chan.channel_id(),
1408                         short_channel_id: chan.get_short_channel_id().unwrap(),
1409                         node_signature: our_node_sig,
1410                         bitcoin_signature: our_bitcoin_sig,
1411                 })
1412         }
1413
1414         /// Processes HTLCs which are pending waiting on random forward delay.
1415         ///
1416         /// Should only really ever be called in response to an PendingHTLCsForwardable event.
1417         /// Will likely generate further events.
1418         pub fn process_pending_htlc_forwards(&self) {
1419                 let _ = self.total_consistency_lock.read().unwrap();
1420
1421                 let mut new_events = Vec::new();
1422                 let mut failed_forwards = Vec::new();
1423                 {
1424                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1425                         let channel_state = channel_state_lock.borrow_parts();
1426
1427                         if cfg!(not(feature = "fuzztarget")) && Instant::now() < *channel_state.next_forward {
1428                                 return;
1429                         }
1430
1431                         for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1432                                 if short_chan_id != 0 {
1433                                         let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1434                                                 Some(chan_id) => chan_id.clone(),
1435                                                 None => {
1436                                                         failed_forwards.reserve(pending_forwards.len());
1437                                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1438                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1439                                                                         short_channel_id: prev_short_channel_id,
1440                                                                         htlc_id: prev_htlc_id,
1441                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1442                                                                 });
1443                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
1444                                                         }
1445                                                         continue;
1446                                                 }
1447                                         };
1448                                         let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();
1449
1450                                         let mut add_htlc_msgs = Vec::new();
1451                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1452                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1453                                                         short_channel_id: prev_short_channel_id,
1454                                                         htlc_id: prev_htlc_id,
1455                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1456                                                 });
1457                                                 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()) {
1458                                                         Err(_e) => {
1459                                                                 let chan_update = self.get_channel_update(forward_chan).unwrap();
1460                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x1000 | 7, Some(chan_update)));
1461                                                                 continue;
1462                                                         },
1463                                                         Ok(update_add) => {
1464                                                                 match update_add {
1465                                                                         Some(msg) => { add_htlc_msgs.push(msg); },
1466                                                                         None => {
1467                                                                                 // Nothing to do here...we're waiting on a remote
1468                                                                                 // revoke_and_ack before we can add anymore HTLCs. The Channel
1469                                                                                 // will automatically handle building the update_add_htlc and
1470                                                                                 // commitment_signed messages when we can.
1471                                                                                 // TODO: Do some kind of timer to set the channel as !is_live()
1472                                                                                 // as we don't really want others relying on us relaying through
1473                                                                                 // this channel currently :/.
1474                                                                         }
1475                                                                 }
1476                                                         }
1477                                                 }
1478                                         }
1479
1480                                         if !add_htlc_msgs.is_empty() {
1481                                                 let (commitment_msg, monitor) = match forward_chan.send_commitment() {
1482                                                         Ok(res) => res,
1483                                                         Err(e) => {
1484                                                                 if let ChannelError::Ignore(_) = e {
1485                                                                         panic!("Stated return value requirements in send_commitment() were not met");
1486                                                                 }
1487                                                                 //TODO: Handle...this is bad!
1488                                                                 continue;
1489                                                         },
1490                                                 };
1491                                                 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
1492                                                         unimplemented!();
1493                                                 }
1494                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1495                                                         node_id: forward_chan.get_their_node_id(),
1496                                                         updates: msgs::CommitmentUpdate {
1497                                                                 update_add_htlcs: add_htlc_msgs,
1498                                                                 update_fulfill_htlcs: Vec::new(),
1499                                                                 update_fail_htlcs: Vec::new(),
1500                                                                 update_fail_malformed_htlcs: Vec::new(),
1501                                                                 update_fee: None,
1502                                                                 commitment_signed: commitment_msg,
1503                                                         },
1504                                                 });
1505                                         }
1506                                 } else {
1507                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1508                                                 let prev_hop_data = HTLCPreviousHopData {
1509                                                         short_channel_id: prev_short_channel_id,
1510                                                         htlc_id: prev_htlc_id,
1511                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1512                                                 };
1513                                                 match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
1514                                                         hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(prev_hop_data),
1515                                                         hash_map::Entry::Vacant(entry) => { entry.insert(vec![prev_hop_data]); },
1516                                                 };
1517                                                 new_events.push(events::Event::PaymentReceived {
1518                                                         payment_hash: forward_info.payment_hash,
1519                                                         amt: forward_info.amt_to_forward,
1520                                                 });
1521                                         }
1522                                 }
1523                         }
1524                 }
1525
1526                 for (htlc_source, payment_hash, failure_code, update) in failed_forwards.drain(..) {
1527                         match update {
1528                                 None => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code, data: Vec::new() }),
1529                                 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() }),
1530                         };
1531                 }
1532
1533                 if new_events.is_empty() { return }
1534                 let mut events = self.pending_events.lock().unwrap();
1535                 events.append(&mut new_events);
1536         }
1537
1538         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect after a PaymentReceived event.
1539         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash, reason: PaymentFailReason) -> bool {
1540                 let _ = self.total_consistency_lock.read().unwrap();
1541
1542                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1543                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(payment_hash);
1544                 if let Some(mut sources) = removed_source {
1545                         for htlc_with_hash in sources.drain(..) {
1546                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1547                                 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() });
1548                         }
1549                         true
1550                 } else { false }
1551         }
1552
1553         /// Fails an HTLC backwards to the sender of it to us.
1554         /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
1555         /// There are several callsites that do stupid things like loop over a list of payment_hashes
1556         /// to fail and take the channel_state lock for each iteration (as we take ownership and may
1557         /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
1558         /// still-available channels.
1559         fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
1560                 match source {
1561                         HTLCSource::OutboundRoute { ref route, .. } => {
1562                                 log_trace!(self, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1563                                 mem::drop(channel_state_lock);
1564                                 match &onion_error {
1565                                         &HTLCFailReason::ErrorPacket { ref err } => {
1566 #[cfg(test)]
1567                                                 let (channel_update, payment_retryable, onion_error_code) = self.process_onion_failure(&source, err.data.clone());
1568 #[cfg(not(test))]
1569                                                 let (channel_update, payment_retryable, _) = self.process_onion_failure(&source, err.data.clone());
1570                                                 // TODO: If we decided to blame ourselves (or one of our channels) in
1571                                                 // process_onion_failure we should close that channel as it implies our
1572                                                 // next-hop is needlessly blaming us!
1573                                                 if let Some(update) = channel_update {
1574                                                         self.channel_state.lock().unwrap().pending_msg_events.push(
1575                                                                 events::MessageSendEvent::PaymentFailureNetworkUpdate {
1576                                                                         update,
1577                                                                 }
1578                                                         );
1579                                                 }
1580                                                 self.pending_events.lock().unwrap().push(
1581                                                         events::Event::PaymentFailed {
1582                                                                 payment_hash: payment_hash.clone(),
1583                                                                 rejected_by_dest: !payment_retryable,
1584 #[cfg(test)]
1585                                                                 error_code: onion_error_code
1586                                                         }
1587                                                 );
1588                                         },
1589                                         &HTLCFailReason::Reason {
1590 #[cfg(test)]
1591                                                         ref failure_code,
1592                                                         .. } => {
1593                                                 // we get a fail_malformed_htlc from the first hop
1594                                                 // TODO: We'd like to generate a PaymentFailureNetworkUpdate for temporary
1595                                                 // failures here, but that would be insufficient as Router::get_route
1596                                                 // generally ignores its view of our own channels as we provide them via
1597                                                 // ChannelDetails.
1598                                                 // TODO: For non-temporary failures, we really should be closing the
1599                                                 // channel here as we apparently can't relay through them anyway.
1600                                                 self.pending_events.lock().unwrap().push(
1601                                                         events::Event::PaymentFailed {
1602                                                                 payment_hash: payment_hash.clone(),
1603                                                                 rejected_by_dest: route.hops.len() == 1,
1604 #[cfg(test)]
1605                                                                 error_code: Some(*failure_code),
1606                                                         }
1607                                                 );
1608                                         }
1609                                 }
1610                         },
1611                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
1612                                 let err_packet = match onion_error {
1613                                         HTLCFailReason::Reason { failure_code, data } => {
1614                                                 log_trace!(self, "Failing HTLC with payment_hash {} backwards from us with code {}", log_bytes!(payment_hash.0), failure_code);
1615                                                 let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1616                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1617                                         },
1618                                         HTLCFailReason::ErrorPacket { err } => {
1619                                                 log_trace!(self, "Failing HTLC with payment_hash {} backwards with pre-built ErrorPacket", log_bytes!(payment_hash.0));
1620                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1621                                         }
1622                                 };
1623
1624                                 let channel_state = channel_state_lock.borrow_parts();
1625
1626                                 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1627                                         Some(chan_id) => chan_id.clone(),
1628                                         None => return
1629                                 };
1630
1631                                 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1632                                 match chan.get_update_fail_htlc_and_commit(htlc_id, err_packet) {
1633                                         Ok(Some((msg, commitment_msg, chan_monitor))) => {
1634                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1635                                                         unimplemented!();
1636                                                 }
1637                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1638                                                         node_id: chan.get_their_node_id(),
1639                                                         updates: msgs::CommitmentUpdate {
1640                                                                 update_add_htlcs: Vec::new(),
1641                                                                 update_fulfill_htlcs: Vec::new(),
1642                                                                 update_fail_htlcs: vec![msg],
1643                                                                 update_fail_malformed_htlcs: Vec::new(),
1644                                                                 update_fee: None,
1645                                                                 commitment_signed: commitment_msg,
1646                                                         },
1647                                                 });
1648                                         },
1649                                         Ok(None) => {},
1650                                         Err(_e) => {
1651                                                 //TODO: Do something with e?
1652                                                 return;
1653                                         },
1654                                 }
1655                         },
1656                 }
1657         }
1658
1659         /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1660         /// generating message events for the net layer to claim the payment, if possible. Thus, you
1661         /// should probably kick the net layer to go send messages if this returns true!
1662         ///
1663         /// May panic if called except in response to a PaymentReceived event.
1664         pub fn claim_funds(&self, payment_preimage: PaymentPreimage) -> bool {
1665                 let mut sha = Sha256::new();
1666                 sha.input(&payment_preimage.0[..]);
1667                 let mut payment_hash = PaymentHash([0; 32]);
1668                 sha.result(&mut payment_hash.0[..]);
1669
1670                 let _ = self.total_consistency_lock.read().unwrap();
1671
1672                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1673                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&payment_hash);
1674                 if let Some(mut sources) = removed_source {
1675                         for htlc_with_hash in sources.drain(..) {
1676                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1677                                 self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_preimage);
1678                         }
1679                         true
1680                 } else { false }
1681         }
1682         fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_preimage: PaymentPreimage) {
1683                 match source {
1684                         HTLCSource::OutboundRoute { .. } => {
1685                                 mem::drop(channel_state_lock);
1686                                 let mut pending_events = self.pending_events.lock().unwrap();
1687                                 pending_events.push(events::Event::PaymentSent {
1688                                         payment_preimage
1689                                 });
1690                         },
1691                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, .. }) => {
1692                                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1693                                 let channel_state = channel_state_lock.borrow_parts();
1694
1695                                 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1696                                         Some(chan_id) => chan_id.clone(),
1697                                         None => {
1698                                                 // TODO: There is probably a channel manager somewhere that needs to
1699                                                 // learn the preimage as the channel already hit the chain and that's
1700                                                 // why its missing.
1701                                                 return
1702                                         }
1703                                 };
1704
1705                                 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1706                                 match chan.get_update_fulfill_htlc_and_commit(htlc_id, payment_preimage) {
1707                                         Ok((msgs, monitor_option)) => {
1708                                                 if let Some(chan_monitor) = monitor_option {
1709                                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1710                                                                 unimplemented!();// but def dont push the event...
1711                                                         }
1712                                                 }
1713                                                 if let Some((msg, commitment_signed)) = msgs {
1714                                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1715                                                                 node_id: chan.get_their_node_id(),
1716                                                                 updates: msgs::CommitmentUpdate {
1717                                                                         update_add_htlcs: Vec::new(),
1718                                                                         update_fulfill_htlcs: vec![msg],
1719                                                                         update_fail_htlcs: Vec::new(),
1720                                                                         update_fail_malformed_htlcs: Vec::new(),
1721                                                                         update_fee: None,
1722                                                                         commitment_signed,
1723                                                                 }
1724                                                         });
1725                                                 }
1726                                         },
1727                                         Err(_e) => {
1728                                                 // TODO: There is probably a channel manager somewhere that needs to
1729                                                 // learn the preimage as the channel may be about to hit the chain.
1730                                                 //TODO: Do something with e?
1731                                                 return
1732                                         },
1733                                 }
1734                         },
1735                 }
1736         }
1737
1738         /// Gets the node_id held by this ChannelManager
1739         pub fn get_our_node_id(&self) -> PublicKey {
1740                 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
1741         }
1742
1743         /// Used to restore channels to normal operation after a
1744         /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
1745         /// operation.
1746         pub fn test_restore_channel_monitor(&self) {
1747                 let mut close_results = Vec::new();
1748                 let mut htlc_forwards = Vec::new();
1749                 let mut htlc_failures = Vec::new();
1750                 let _ = self.total_consistency_lock.read().unwrap();
1751
1752                 {
1753                         let mut channel_lock = self.channel_state.lock().unwrap();
1754                         let channel_state = channel_lock.borrow_parts();
1755                         let short_to_id = channel_state.short_to_id;
1756                         let pending_msg_events = channel_state.pending_msg_events;
1757                         channel_state.by_id.retain(|_, channel| {
1758                                 if channel.is_awaiting_monitor_update() {
1759                                         let chan_monitor = channel.channel_monitor();
1760                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1761                                                 match e {
1762                                                         ChannelMonitorUpdateErr::PermanentFailure => {
1763                                                                 // TODO: There may be some pending HTLCs that we intended to fail
1764                                                                 // backwards when a monitor update failed. We should make sure
1765                                                                 // knowledge of those gets moved into the appropriate in-memory
1766                                                                 // ChannelMonitor and they get failed backwards once we get
1767                                                                 // on-chain confirmations.
1768                                                                 // Note I think #198 addresses this, so once its merged a test
1769                                                                 // should be written.
1770                                                                 if let Some(short_id) = channel.get_short_channel_id() {
1771                                                                         short_to_id.remove(&short_id);
1772                                                                 }
1773                                                                 close_results.push(channel.force_shutdown());
1774                                                                 if let Ok(update) = self.get_channel_update(&channel) {
1775                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1776                                                                                 msg: update
1777                                                                         });
1778                                                                 }
1779                                                                 false
1780                                                         },
1781                                                         ChannelMonitorUpdateErr::TemporaryFailure => true,
1782                                                 }
1783                                         } else {
1784                                                 let (raa, commitment_update, order, pending_forwards, mut pending_failures) = channel.monitor_updating_restored();
1785                                                 if !pending_forwards.is_empty() {
1786                                                         htlc_forwards.push((channel.get_short_channel_id().expect("We can't have pending forwards before funding confirmation"), pending_forwards));
1787                                                 }
1788                                                 htlc_failures.append(&mut pending_failures);
1789
1790                                                 macro_rules! handle_cs { () => {
1791                                                         if let Some(update) = commitment_update {
1792                                                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1793                                                                         node_id: channel.get_their_node_id(),
1794                                                                         updates: update,
1795                                                                 });
1796                                                         }
1797                                                 } }
1798                                                 macro_rules! handle_raa { () => {
1799                                                         if let Some(revoke_and_ack) = raa {
1800                                                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
1801                                                                         node_id: channel.get_their_node_id(),
1802                                                                         msg: revoke_and_ack,
1803                                                                 });
1804                                                         }
1805                                                 } }
1806                                                 match order {
1807                                                         RAACommitmentOrder::CommitmentFirst => {
1808                                                                 handle_cs!();
1809                                                                 handle_raa!();
1810                                                         },
1811                                                         RAACommitmentOrder::RevokeAndACKFirst => {
1812                                                                 handle_raa!();
1813                                                                 handle_cs!();
1814                                                         },
1815                                                 }
1816                                                 true
1817                                         }
1818                                 } else { true }
1819                         });
1820                 }
1821
1822                 for failure in htlc_failures.drain(..) {
1823                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
1824                 }
1825                 self.forward_htlcs(&mut htlc_forwards[..]);
1826
1827                 for res in close_results.drain(..) {
1828                         self.finish_force_close_channel(res);
1829                 }
1830         }
1831
1832         fn internal_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
1833                 if msg.chain_hash != self.genesis_hash {
1834                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash", msg.temporary_channel_id.clone()));
1835                 }
1836
1837                 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)
1838                         .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
1839                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1840                 let channel_state = channel_state_lock.borrow_parts();
1841                 match channel_state.by_id.entry(channel.channel_id()) {
1842                         hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!", msg.temporary_channel_id.clone())),
1843                         hash_map::Entry::Vacant(entry) => {
1844                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
1845                                         node_id: their_node_id.clone(),
1846                                         msg: channel.get_accept_channel(),
1847                                 });
1848                                 entry.insert(channel);
1849                         }
1850                 }
1851                 Ok(())
1852         }
1853
1854         fn internal_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
1855                 let (value, output_script, user_id) = {
1856                         let mut channel_lock = self.channel_state.lock().unwrap();
1857                         let channel_state = channel_lock.borrow_parts();
1858                         match channel_state.by_id.entry(msg.temporary_channel_id) {
1859                                 hash_map::Entry::Occupied(mut chan) => {
1860                                         if chan.get().get_their_node_id() != *their_node_id {
1861                                                 //TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
1862                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1863                                         }
1864                                         try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration), channel_state, chan);
1865                                         (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
1866                                 },
1867                                 //TODO: same as above
1868                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1869                         }
1870                 };
1871                 let mut pending_events = self.pending_events.lock().unwrap();
1872                 pending_events.push(events::Event::FundingGenerationReady {
1873                         temporary_channel_id: msg.temporary_channel_id,
1874                         channel_value_satoshis: value,
1875                         output_script: output_script,
1876                         user_channel_id: user_id,
1877                 });
1878                 Ok(())
1879         }
1880
1881         fn internal_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
1882                 let ((funding_msg, monitor_update), chan) = {
1883                         let mut channel_lock = self.channel_state.lock().unwrap();
1884                         let channel_state = channel_lock.borrow_parts();
1885                         match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
1886                                 hash_map::Entry::Occupied(mut chan) => {
1887                                         if chan.get().get_their_node_id() != *their_node_id {
1888                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1889                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1890                                         }
1891                                         (try_chan_entry!(self, chan.get_mut().funding_created(msg), channel_state, chan), chan.remove())
1892                                 },
1893                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1894                         }
1895                 };
1896                 // Because we have exclusive ownership of the channel here we can release the channel_state
1897                 // lock before add_update_monitor
1898                 if let Err(_e) = self.monitor.add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) {
1899                         unimplemented!();
1900                 }
1901                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1902                 let channel_state = channel_state_lock.borrow_parts();
1903                 match channel_state.by_id.entry(funding_msg.channel_id) {
1904                         hash_map::Entry::Occupied(_) => {
1905                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id", funding_msg.channel_id))
1906                         },
1907                         hash_map::Entry::Vacant(e) => {
1908                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
1909                                         node_id: their_node_id.clone(),
1910                                         msg: funding_msg,
1911                                 });
1912                                 e.insert(chan);
1913                         }
1914                 }
1915                 Ok(())
1916         }
1917
1918         fn internal_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
1919                 let (funding_txo, user_id) = {
1920                         let mut channel_lock = self.channel_state.lock().unwrap();
1921                         let channel_state = channel_lock.borrow_parts();
1922                         match channel_state.by_id.entry(msg.channel_id) {
1923                                 hash_map::Entry::Occupied(mut chan) => {
1924                                         if chan.get().get_their_node_id() != *their_node_id {
1925                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1926                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1927                                         }
1928                                         let chan_monitor = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
1929                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1930                                                 unimplemented!();
1931                                         }
1932                                         (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())
1933                                 },
1934                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1935                         }
1936                 };
1937                 let mut pending_events = self.pending_events.lock().unwrap();
1938                 pending_events.push(events::Event::FundingBroadcastSafe {
1939                         funding_txo: funding_txo,
1940                         user_channel_id: user_id,
1941                 });
1942                 Ok(())
1943         }
1944
1945         fn internal_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), MsgHandleErrInternal> {
1946                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1947                 let channel_state = channel_state_lock.borrow_parts();
1948                 match channel_state.by_id.entry(msg.channel_id) {
1949                         hash_map::Entry::Occupied(mut chan) => {
1950                                 if chan.get().get_their_node_id() != *their_node_id {
1951                                         //TODO: here and below MsgHandleErrInternal, #153 case
1952                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1953                                 }
1954                                 try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
1955                                 if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
1956                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
1957                                                 node_id: their_node_id.clone(),
1958                                                 msg: announcement_sigs,
1959                                         });
1960                                 }
1961                                 Ok(())
1962                         },
1963                         hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1964                 }
1965         }
1966
1967         fn internal_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
1968                 let (mut dropped_htlcs, chan_option) = {
1969                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1970                         let channel_state = channel_state_lock.borrow_parts();
1971
1972                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1973                                 hash_map::Entry::Occupied(mut chan_entry) => {
1974                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1975                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1976                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1977                                         }
1978                                         let (shutdown, closing_signed, dropped_htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg), channel_state, chan_entry);
1979                                         if let Some(msg) = shutdown {
1980                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
1981                                                         node_id: their_node_id.clone(),
1982                                                         msg,
1983                                                 });
1984                                         }
1985                                         if let Some(msg) = closing_signed {
1986                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1987                                                         node_id: their_node_id.clone(),
1988                                                         msg,
1989                                                 });
1990                                         }
1991                                         if chan_entry.get().is_shutdown() {
1992                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1993                                                         channel_state.short_to_id.remove(&short_id);
1994                                                 }
1995                                                 (dropped_htlcs, Some(chan_entry.remove_entry().1))
1996                                         } else { (dropped_htlcs, None) }
1997                                 },
1998                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1999                         }
2000                 };
2001                 for htlc_source in dropped_htlcs.drain(..) {
2002                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
2003                 }
2004                 if let Some(chan) = chan_option {
2005                         if let Ok(update) = self.get_channel_update(&chan) {
2006                                 let mut channel_state = self.channel_state.lock().unwrap();
2007                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2008                                         msg: update
2009                                 });
2010                         }
2011                 }
2012                 Ok(())
2013         }
2014
2015         fn internal_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
2016                 let (tx, chan_option) = {
2017                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2018                         let channel_state = channel_state_lock.borrow_parts();
2019                         match channel_state.by_id.entry(msg.channel_id.clone()) {
2020                                 hash_map::Entry::Occupied(mut chan_entry) => {
2021                                         if chan_entry.get().get_their_node_id() != *their_node_id {
2022                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2023                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2024                                         }
2025                                         let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg), channel_state, chan_entry);
2026                                         if let Some(msg) = closing_signed {
2027                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2028                                                         node_id: their_node_id.clone(),
2029                                                         msg,
2030                                                 });
2031                                         }
2032                                         if tx.is_some() {
2033                                                 // We're done with this channel, we've got a signed closing transaction and
2034                                                 // will send the closing_signed back to the remote peer upon return. This
2035                                                 // also implies there are no pending HTLCs left on the channel, so we can
2036                                                 // fully delete it from tracking (the channel monitor is still around to
2037                                                 // watch for old state broadcasts)!
2038                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2039                                                         channel_state.short_to_id.remove(&short_id);
2040                                                 }
2041                                                 (tx, Some(chan_entry.remove_entry().1))
2042                                         } else { (tx, None) }
2043                                 },
2044                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2045                         }
2046                 };
2047                 if let Some(broadcast_tx) = tx {
2048                         self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
2049                 }
2050                 if let Some(chan) = chan_option {
2051                         if let Ok(update) = self.get_channel_update(&chan) {
2052                                 let mut channel_state = self.channel_state.lock().unwrap();
2053                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2054                                         msg: update
2055                                 });
2056                         }
2057                 }
2058                 Ok(())
2059         }
2060
2061         fn internal_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
2062                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
2063                 //determine the state of the payment based on our response/if we forward anything/the time
2064                 //we take to respond. We should take care to avoid allowing such an attack.
2065                 //
2066                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
2067                 //us repeatedly garbled in different ways, and compare our error messages, which are
2068                 //encrypted with the same key. Its not immediately obvious how to usefully exploit that,
2069                 //but we should prevent it anyway.
2070
2071                 let (mut pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
2072                 let channel_state = channel_state_lock.borrow_parts();
2073
2074                 match channel_state.by_id.entry(msg.channel_id) {
2075                         hash_map::Entry::Occupied(mut chan) => {
2076                                 if chan.get().get_their_node_id() != *their_node_id {
2077                                         //TODO: here MsgHandleErrInternal, #153 case
2078                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2079                                 }
2080                                 if !chan.get().is_usable() {
2081                                         // If the update_add is completely bogus, the call will Err and we will close,
2082                                         // but if we've sent a shutdown and they haven't acknowledged it yet, we just
2083                                         // want to reject the new HTLC and fail it backwards instead of forwarding.
2084                                         if let PendingHTLCStatus::Forward(PendingForwardHTLCInfo { incoming_shared_secret, .. }) = pending_forward_info {
2085                                                 let chan_update = self.get_channel_update(chan.get());
2086                                                 pending_forward_info = PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
2087                                                         channel_id: msg.channel_id,
2088                                                         htlc_id: msg.htlc_id,
2089                                                         reason: if let Ok(update) = chan_update {
2090                                                                 // TODO: Note that |20 is defined as "channel FROM the processing
2091                                                                 // node has been disabled" (emphasis mine), which seems to imply
2092                                                                 // that we can't return |20 for an inbound channel being disabled.
2093                                                                 // This probably needs a spec update but should definitely be
2094                                                                 // allowed.
2095                                                                 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x1000|20, &{
2096                                                                         let mut res = Vec::with_capacity(8 + 128);
2097                                                                         res.extend_from_slice(&byte_utils::be16_to_array(update.contents.flags));
2098                                                                         res.extend_from_slice(&update.encode_with_len()[..]);
2099                                                                         res
2100                                                                 }[..])
2101                                                         } else {
2102                                                                 // This can only happen if the channel isn't in the fully-funded
2103                                                                 // state yet, implying our counterparty is trying to route payments
2104                                                                 // over the channel back to themselves (cause no one else should
2105                                                                 // know the short_id is a lightning channel yet). We should have no
2106                                                                 // problem just calling this unknown_next_peer
2107                                                                 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x4000|10, &[])
2108                                                         },
2109                                                 }));
2110                                         }
2111                                 }
2112                                 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info), channel_state, chan);
2113                         },
2114                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2115                 }
2116                 Ok(())
2117         }
2118
2119         fn internal_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
2120                 let mut channel_lock = self.channel_state.lock().unwrap();
2121                 let htlc_source = {
2122                         let channel_state = channel_lock.borrow_parts();
2123                         match channel_state.by_id.entry(msg.channel_id) {
2124                                 hash_map::Entry::Occupied(mut chan) => {
2125                                         if chan.get().get_their_node_id() != *their_node_id {
2126                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2127                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2128                                         }
2129                                         try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), channel_state, chan)
2130                                 },
2131                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2132                         }
2133                 };
2134                 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
2135                 Ok(())
2136         }
2137
2138         // Process failure we got back from upstream on a payment we sent. Returns update and a boolean
2139         // indicating that the payment itself failed
2140         fn process_onion_failure(&self, htlc_source: &HTLCSource, mut packet_decrypted: Vec<u8>) -> (Option<msgs::HTLCFailChannelUpdate>, bool, Option<u16>) {
2141                 if let &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } = htlc_source {
2142
2143                         let mut res = None;
2144                         let mut htlc_msat = *first_hop_htlc_msat;
2145                         let mut error_code_ret = None;
2146                         let mut next_route_hop_ix = 0;
2147                         let mut is_from_final_node = false;
2148
2149                         // Handle packed channel/node updates for passing back for the route handler
2150                         Self::construct_onion_keys_callback(&self.secp_ctx, route, session_priv, |shared_secret, _, _, route_hop| {
2151                                 next_route_hop_ix += 1;
2152                                 if res.is_some() { return; }
2153
2154                                 let amt_to_forward = htlc_msat - route_hop.fee_msat;
2155                                 htlc_msat = amt_to_forward;
2156
2157                                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret[..]);
2158
2159                                 let mut decryption_tmp = Vec::with_capacity(packet_decrypted.len());
2160                                 decryption_tmp.resize(packet_decrypted.len(), 0);
2161                                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
2162                                 chacha.process(&packet_decrypted, &mut decryption_tmp[..]);
2163                                 packet_decrypted = decryption_tmp;
2164
2165                                 is_from_final_node = route.hops.last().unwrap().pubkey == route_hop.pubkey;
2166
2167                                 if let Ok(err_packet) = msgs::DecodedOnionErrorPacket::read(&mut Cursor::new(&packet_decrypted)) {
2168                                         let um = ChannelManager::gen_um_from_shared_secret(&shared_secret[..]);
2169                                         let mut hmac = Hmac::new(Sha256::new(), &um);
2170                                         hmac.input(&err_packet.encode()[32..]);
2171                                         let mut calc_tag = [0u8; 32];
2172                                         hmac.raw_result(&mut calc_tag);
2173
2174                                         if crypto::util::fixed_time_eq(&calc_tag, &err_packet.hmac) {
2175                                                 if let Some(error_code_slice) = err_packet.failuremsg.get(0..2) {
2176                                                         const PERM: u16 = 0x4000;
2177                                                         const NODE: u16 = 0x2000;
2178                                                         const UPDATE: u16 = 0x1000;
2179
2180                                                         let error_code = byte_utils::slice_to_be16(&error_code_slice);
2181                                                         error_code_ret = Some(error_code);
2182
2183                                                         let (debug_field, debug_field_size) = errors::get_onion_debug_field(error_code);
2184
2185                                                         // indicate that payment parameter has failed and no need to
2186                                                         // update Route object
2187                                                         let payment_failed = (match error_code & 0xff {
2188                                                                 15|16|17|18|19 => true,
2189                                                                 _ => false,
2190                                                         } && is_from_final_node) // PERM bit observed below even this error is from the intermediate nodes
2191                                                         || error_code == 21; // Special case error 21 as the Route object is bogus, TODO: Maybe fail the node if the CLTV was reasonable?
2192
2193                                                         let mut fail_channel_update = None;
2194
2195                                                         if error_code & NODE == NODE {
2196                                                                 fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure { node_id: route_hop.pubkey, is_permanent: error_code & PERM == PERM });
2197                                                         }
2198                                                         else if error_code & PERM == PERM {
2199                                                                 fail_channel_update = if payment_failed {None} else {Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
2200                                                                         short_channel_id: route.hops[next_route_hop_ix - if next_route_hop_ix == route.hops.len() { 1 } else { 0 }].short_channel_id,
2201                                                                         is_permanent: true,
2202                                                                 })};
2203                                                         }
2204                                                         else if error_code & UPDATE == UPDATE {
2205                                                                 if let Some(update_len_slice) = err_packet.failuremsg.get(debug_field_size+2..debug_field_size+4) {
2206                                                                         let update_len = byte_utils::slice_to_be16(&update_len_slice) as usize;
2207                                                                         if let Some(update_slice) = err_packet.failuremsg.get(debug_field_size + 4..debug_field_size + 4 + update_len) {
2208                                                                                 if let Ok(chan_update) = msgs::ChannelUpdate::read(&mut Cursor::new(&update_slice)) {
2209                                                                                         // if channel_update should NOT have caused the failure:
2210                                                                                         // MAY treat the channel_update as invalid.
2211                                                                                         let is_chan_update_invalid = match error_code & 0xff {
2212                                                                                                 7 => false,
2213                                                                                                 11 => amt_to_forward > chan_update.contents.htlc_minimum_msat,
2214                                                                                                 12 => {
2215                                                                                                         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) });
2216                                                                                                         new_fee.is_some() && route_hop.fee_msat >= new_fee.unwrap()
2217                                                                                                 }
2218                                                                                                 13 => route_hop.cltv_expiry_delta as u16 >= chan_update.contents.cltv_expiry_delta,
2219                                                                                                 14 => false, // expiry_too_soon; always valid?
2220                                                                                                 20 => chan_update.contents.flags & 2 == 0,
2221                                                                                                 _ => false, // unknown error code; take channel_update as valid
2222                                                                                         };
2223                                                                                         fail_channel_update = if is_chan_update_invalid {
2224                                                                                                 // This probably indicates the node which forwarded
2225                                                                                                 // to the node in question corrupted something.
2226                                                                                                 Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
2227                                                                                                         short_channel_id: route_hop.short_channel_id,
2228                                                                                                         is_permanent: true,
2229                                                                                                 })
2230                                                                                         } else {
2231                                                                                                 Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {
2232                                                                                                         msg: chan_update,
2233                                                                                                 })
2234                                                                                         };
2235                                                                                 }
2236                                                                         }
2237                                                                 }
2238                                                                 if fail_channel_update.is_none() {
2239                                                                         // They provided an UPDATE which was obviously bogus, not worth
2240                                                                         // trying to relay through them anymore.
2241                                                                         fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2242                                                                                 node_id: route_hop.pubkey,
2243                                                                                 is_permanent: true,
2244                                                                         });
2245                                                                 }
2246                                                         } else if !payment_failed {
2247                                                                 // We can't understand their error messages and they failed to
2248                                                                 // forward...they probably can't understand our forwards so its
2249                                                                 // really not worth trying any further.
2250                                                                 fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2251                                                                         node_id: route_hop.pubkey,
2252                                                                         is_permanent: true,
2253                                                                 });
2254                                                         }
2255
2256                                                         // TODO: Here (and a few other places) we assume that BADONION errors
2257                                                         // are always "sourced" from the node previous to the one which failed
2258                                                         // to decode the onion.
2259                                                         res = Some((fail_channel_update, !(error_code & PERM == PERM && is_from_final_node)));
2260
2261                                                         let (description, title) = errors::get_onion_error_description(error_code);
2262                                                         if debug_field_size > 0 && err_packet.failuremsg.len() >= 4 + debug_field_size {
2263                                                                 log_warn!(self, "Onion Error[{}({:#x}) {}({})] {}", title, error_code, debug_field, log_bytes!(&err_packet.failuremsg[4..4+debug_field_size]), description);
2264                                                         }
2265                                                         else {
2266                                                                 log_warn!(self, "Onion Error[{}({:#x})] {}", title, error_code, description);
2267                                                         }
2268                                                 } else {
2269                                                         // Useless packet that we can't use but it passed HMAC, so it
2270                                                         // definitely came from the peer in question
2271                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2272                                                                 node_id: route_hop.pubkey,
2273                                                                 is_permanent: true,
2274                                                         }), !is_from_final_node));
2275                                                 }
2276                                         }
2277                                 }
2278                         }).expect("Route that we sent via spontaneously grew invalid keys in the middle of it?");
2279                         if let Some((channel_update, payment_retryable)) = res {
2280                                 (channel_update, payment_retryable, error_code_ret)
2281                         } else {
2282                                 // only not set either packet unparseable or hmac does not match with any
2283                                 // payment not retryable only when garbage is from the final node
2284                                 (None, !is_from_final_node, None)
2285                         }
2286                 } else { unreachable!(); }
2287         }
2288
2289         fn internal_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
2290                 let mut channel_lock = self.channel_state.lock().unwrap();
2291                 let channel_state = channel_lock.borrow_parts();
2292                 match channel_state.by_id.entry(msg.channel_id) {
2293                         hash_map::Entry::Occupied(mut chan) => {
2294                                 if chan.get().get_their_node_id() != *their_node_id {
2295                                         //TODO: here and below MsgHandleErrInternal, #153 case
2296                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2297                                 }
2298                                 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::ErrorPacket { err: msg.reason.clone() }), channel_state, chan);
2299                         },
2300                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2301                 }
2302                 Ok(())
2303         }
2304
2305         fn internal_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
2306                 let mut channel_lock = self.channel_state.lock().unwrap();
2307                 let channel_state = channel_lock.borrow_parts();
2308                 match channel_state.by_id.entry(msg.channel_id) {
2309                         hash_map::Entry::Occupied(mut chan) => {
2310                                 if chan.get().get_their_node_id() != *their_node_id {
2311                                         //TODO: here and below MsgHandleErrInternal, #153 case
2312                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2313                                 }
2314                                 if (msg.failure_code & 0x8000) == 0 {
2315                                         try_chan_entry!(self, Err(ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set")), channel_state, chan);
2316                                 }
2317                                 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);
2318                                 Ok(())
2319                         },
2320                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2321                 }
2322         }
2323
2324         fn internal_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
2325                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2326                 let channel_state = channel_state_lock.borrow_parts();
2327                 match channel_state.by_id.entry(msg.channel_id) {
2328                         hash_map::Entry::Occupied(mut chan) => {
2329                                 if chan.get().get_their_node_id() != *their_node_id {
2330                                         //TODO: here and below MsgHandleErrInternal, #153 case
2331                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2332                                 }
2333                                 let (revoke_and_ack, commitment_signed, closing_signed, chan_monitor) =
2334                                         try_chan_entry!(self, chan.get_mut().commitment_signed(&msg, &*self.fee_estimator), channel_state, chan);
2335                                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2336                                         return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, commitment_signed.is_some());
2337                                         //TODO: Rebroadcast closing_signed if present on monitor update restoration
2338                                 }
2339                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2340                                         node_id: their_node_id.clone(),
2341                                         msg: revoke_and_ack,
2342                                 });
2343                                 if let Some(msg) = commitment_signed {
2344                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2345                                                 node_id: their_node_id.clone(),
2346                                                 updates: msgs::CommitmentUpdate {
2347                                                         update_add_htlcs: Vec::new(),
2348                                                         update_fulfill_htlcs: Vec::new(),
2349                                                         update_fail_htlcs: Vec::new(),
2350                                                         update_fail_malformed_htlcs: Vec::new(),
2351                                                         update_fee: None,
2352                                                         commitment_signed: msg,
2353                                                 },
2354                                         });
2355                                 }
2356                                 if let Some(msg) = closing_signed {
2357                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2358                                                 node_id: their_node_id.clone(),
2359                                                 msg,
2360                                         });
2361                                 }
2362                                 Ok(())
2363                         },
2364                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2365                 }
2366         }
2367
2368         #[inline]
2369         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64)>)]) {
2370                 for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
2371                         let mut forward_event = None;
2372                         if !pending_forwards.is_empty() {
2373                                 let mut channel_state = self.channel_state.lock().unwrap();
2374                                 if channel_state.forward_htlcs.is_empty() {
2375                                         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));
2376                                         channel_state.next_forward = forward_event.unwrap();
2377                                 }
2378                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2379                                         match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
2380                                                 hash_map::Entry::Occupied(mut entry) => {
2381                                                         entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info });
2382                                                 },
2383                                                 hash_map::Entry::Vacant(entry) => {
2384                                                         entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info }));
2385                                                 }
2386                                         }
2387                                 }
2388                         }
2389                         match forward_event {
2390                                 Some(time) => {
2391                                         let mut pending_events = self.pending_events.lock().unwrap();
2392                                         pending_events.push(events::Event::PendingHTLCsForwardable {
2393                                                 time_forwardable: time
2394                                         });
2395                                 }
2396                                 None => {},
2397                         }
2398                 }
2399         }
2400
2401         fn internal_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
2402                 let (pending_forwards, mut pending_failures, short_channel_id) = {
2403                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2404                         let channel_state = channel_state_lock.borrow_parts();
2405                         match channel_state.by_id.entry(msg.channel_id) {
2406                                 hash_map::Entry::Occupied(mut chan) => {
2407                                         if chan.get().get_their_node_id() != *their_node_id {
2408                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2409                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2410                                         }
2411                                         let (commitment_update, pending_forwards, pending_failures, closing_signed, chan_monitor) =
2412                                                 try_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &*self.fee_estimator), channel_state, chan);
2413                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2414                                                 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, pending_forwards, pending_failures);
2415                                         }
2416                                         if let Some(updates) = commitment_update {
2417                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2418                                                         node_id: their_node_id.clone(),
2419                                                         updates,
2420                                                 });
2421                                         }
2422                                         if let Some(msg) = closing_signed {
2423                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2424                                                         node_id: their_node_id.clone(),
2425                                                         msg,
2426                                                 });
2427                                         }
2428                                         (pending_forwards, pending_failures, chan.get().get_short_channel_id().expect("RAA should only work on a short-id-available channel"))
2429                                 },
2430                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2431                         }
2432                 };
2433                 for failure in pending_failures.drain(..) {
2434                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2435                 }
2436                 self.forward_htlcs(&mut [(short_channel_id, pending_forwards)]);
2437
2438                 Ok(())
2439         }
2440
2441         fn internal_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2442                 let mut channel_lock = self.channel_state.lock().unwrap();
2443                 let channel_state = channel_lock.borrow_parts();
2444                 match channel_state.by_id.entry(msg.channel_id) {
2445                         hash_map::Entry::Occupied(mut chan) => {
2446                                 if chan.get().get_their_node_id() != *their_node_id {
2447                                         //TODO: here and below MsgHandleErrInternal, #153 case
2448                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2449                                 }
2450                                 try_chan_entry!(self, chan.get_mut().update_fee(&*self.fee_estimator, &msg), channel_state, chan);
2451                         },
2452                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2453                 }
2454                 Ok(())
2455         }
2456
2457         fn internal_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2458                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2459                 let channel_state = channel_state_lock.borrow_parts();
2460
2461                 match channel_state.by_id.entry(msg.channel_id) {
2462                         hash_map::Entry::Occupied(mut chan) => {
2463                                 if chan.get().get_their_node_id() != *their_node_id {
2464                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2465                                 }
2466                                 if !chan.get().is_usable() {
2467                                         return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Got an announcement_signatures before we were ready for it", action: Some(msgs::ErrorAction::IgnoreError)}));
2468                                 }
2469
2470                                 let our_node_id = self.get_our_node_id();
2471                                 let (announcement, our_bitcoin_sig) =
2472                                         try_chan_entry!(self, chan.get_mut().get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone()), channel_state, chan);
2473
2474                                 let were_node_one = announcement.node_id_1 == our_node_id;
2475                                 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
2476                                 if self.secp_ctx.verify(&msghash, &msg.node_signature, if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 }).is_err() ||
2477                                                 self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 }).is_err() {
2478                                         try_chan_entry!(self, Err(ChannelError::Close("Bad announcement_signatures node_signature")), channel_state, chan);
2479                                 }
2480
2481                                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2482
2483                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
2484                                         msg: msgs::ChannelAnnouncement {
2485                                                 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
2486                                                 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
2487                                                 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
2488                                                 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
2489                                                 contents: announcement,
2490                                         },
2491                                         update_msg: self.get_channel_update(chan.get()).unwrap(), // can only fail if we're not in a ready state
2492                                 });
2493                         },
2494                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2495                 }
2496                 Ok(())
2497         }
2498
2499         fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
2500                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2501                 let channel_state = channel_state_lock.borrow_parts();
2502
2503                 match channel_state.by_id.entry(msg.channel_id) {
2504                         hash_map::Entry::Occupied(mut chan) => {
2505                                 if chan.get().get_their_node_id() != *their_node_id {
2506                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2507                                 }
2508                                 let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, mut order, shutdown) =
2509                                         try_chan_entry!(self, chan.get_mut().channel_reestablish(msg), channel_state, chan);
2510                                 if let Some(monitor) = channel_monitor {
2511                                         if let Err(e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
2512                                                 // channel_reestablish doesn't guarantee the order it returns is sensical
2513                                                 // for the messages it returns, but if we're setting what messages to
2514                                                 // re-transmit on monitor update success, we need to make sure it is sane.
2515                                                 if revoke_and_ack.is_none() {
2516                                                         order = RAACommitmentOrder::CommitmentFirst;
2517                                                 }
2518                                                 if commitment_update.is_none() {
2519                                                         order = RAACommitmentOrder::RevokeAndACKFirst;
2520                                                 }
2521                                                 return_monitor_err!(self, e, channel_state, chan, order);
2522                                                 //TODO: Resend the funding_locked if needed once we get the monitor running again
2523                                         }
2524                                 }
2525                                 if let Some(msg) = funding_locked {
2526                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2527                                                 node_id: their_node_id.clone(),
2528                                                 msg
2529                                         });
2530                                 }
2531                                 macro_rules! send_raa { () => {
2532                                         if let Some(msg) = revoke_and_ack {
2533                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2534                                                         node_id: their_node_id.clone(),
2535                                                         msg
2536                                                 });
2537                                         }
2538                                 } }
2539                                 macro_rules! send_cu { () => {
2540                                         if let Some(updates) = commitment_update {
2541                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2542                                                         node_id: their_node_id.clone(),
2543                                                         updates
2544                                                 });
2545                                         }
2546                                 } }
2547                                 match order {
2548                                         RAACommitmentOrder::RevokeAndACKFirst => {
2549                                                 send_raa!();
2550                                                 send_cu!();
2551                                         },
2552                                         RAACommitmentOrder::CommitmentFirst => {
2553                                                 send_cu!();
2554                                                 send_raa!();
2555                                         },
2556                                 }
2557                                 if let Some(msg) = shutdown {
2558                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2559                                                 node_id: their_node_id.clone(),
2560                                                 msg,
2561                                         });
2562                                 }
2563                                 Ok(())
2564                         },
2565                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2566                 }
2567         }
2568
2569         /// Begin Update fee process. Allowed only on an outbound channel.
2570         /// If successful, will generate a UpdateHTLCs event, so you should probably poll
2571         /// PeerManager::process_events afterwards.
2572         /// Note: This API is likely to change!
2573         #[doc(hidden)]
2574         pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u64) -> Result<(), APIError> {
2575                 let _ = self.total_consistency_lock.read().unwrap();
2576                 let their_node_id;
2577                 let err: Result<(), _> = loop {
2578                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2579                         let channel_state = channel_state_lock.borrow_parts();
2580
2581                         match channel_state.by_id.entry(channel_id) {
2582                                 hash_map::Entry::Vacant(_) => return Err(APIError::APIMisuseError{err: "Failed to find corresponding channel"}),
2583                                 hash_map::Entry::Occupied(mut chan) => {
2584                                         if !chan.get().is_outbound() {
2585                                                 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel"});
2586                                         }
2587                                         if chan.get().is_awaiting_monitor_update() {
2588                                                 return Err(APIError::MonitorUpdateFailed);
2589                                         }
2590                                         if !chan.get().is_live() {
2591                                                 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected"});
2592                                         }
2593                                         their_node_id = chan.get().get_their_node_id();
2594                                         if let Some((update_fee, commitment_signed, chan_monitor)) =
2595                                                         break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw), channel_state, chan)
2596                                         {
2597                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2598                                                         unimplemented!();
2599                                                 }
2600                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2601                                                         node_id: chan.get().get_their_node_id(),
2602                                                         updates: msgs::CommitmentUpdate {
2603                                                                 update_add_htlcs: Vec::new(),
2604                                                                 update_fulfill_htlcs: Vec::new(),
2605                                                                 update_fail_htlcs: Vec::new(),
2606                                                                 update_fail_malformed_htlcs: Vec::new(),
2607                                                                 update_fee: Some(update_fee),
2608                                                                 commitment_signed,
2609                                                         },
2610                                                 });
2611                                         }
2612                                 },
2613                         }
2614                         return Ok(())
2615                 };
2616
2617                 match handle_error!(self, err, their_node_id) {
2618                         Ok(_) => unreachable!(),
2619                         Err(e) => {
2620                                 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
2621                                 } else {
2622                                         log_error!(self, "Got bad keys: {}!", e.err);
2623                                         let mut channel_state = self.channel_state.lock().unwrap();
2624                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
2625                                                 node_id: their_node_id,
2626                                                 action: e.action,
2627                                         });
2628                                 }
2629                                 Err(APIError::APIMisuseError { err: e.err })
2630                         },
2631                 }
2632         }
2633 }
2634
2635 impl events::MessageSendEventsProvider for ChannelManager {
2636         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
2637                 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2638                 // user to serialize a ChannelManager with pending events in it and lose those events on
2639                 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2640                 {
2641                         //TODO: This behavior should be documented.
2642                         for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2643                                 if let Some(preimage) = htlc_update.payment_preimage {
2644                                         log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2645                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2646                                 } else {
2647                                         log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2648                                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
2649                                 }
2650                         }
2651                 }
2652
2653                 let mut ret = Vec::new();
2654                 let mut channel_state = self.channel_state.lock().unwrap();
2655                 mem::swap(&mut ret, &mut channel_state.pending_msg_events);
2656                 ret
2657         }
2658 }
2659
2660 impl events::EventsProvider for ChannelManager {
2661         fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
2662                 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2663                 // user to serialize a ChannelManager with pending events in it and lose those events on
2664                 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2665                 {
2666                         //TODO: This behavior should be documented.
2667                         for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2668                                 if let Some(preimage) = htlc_update.payment_preimage {
2669                                         log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2670                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2671                                 } else {
2672                                         log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2673                                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
2674                                 }
2675                         }
2676                 }
2677
2678                 let mut ret = Vec::new();
2679                 let mut pending_events = self.pending_events.lock().unwrap();
2680                 mem::swap(&mut ret, &mut *pending_events);
2681                 ret
2682         }
2683 }
2684
2685 impl ChainListener for ChannelManager {
2686         fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
2687                 let header_hash = header.bitcoin_hash();
2688                 log_trace!(self, "Block {} at height {} connected with {} txn matched", header_hash, height, txn_matched.len());
2689                 let _ = self.total_consistency_lock.read().unwrap();
2690                 let mut failed_channels = Vec::new();
2691                 {
2692                         let mut channel_lock = self.channel_state.lock().unwrap();
2693                         let channel_state = channel_lock.borrow_parts();
2694                         let short_to_id = channel_state.short_to_id;
2695                         let pending_msg_events = channel_state.pending_msg_events;
2696                         channel_state.by_id.retain(|_, channel| {
2697                                 let chan_res = channel.block_connected(header, height, txn_matched, indexes_of_txn_matched);
2698                                 if let Ok(Some(funding_locked)) = chan_res {
2699                                         pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2700                                                 node_id: channel.get_their_node_id(),
2701                                                 msg: funding_locked,
2702                                         });
2703                                         if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
2704                                                 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2705                                                         node_id: channel.get_their_node_id(),
2706                                                         msg: announcement_sigs,
2707                                                 });
2708                                         }
2709                                         short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
2710                                 } else if let Err(e) = chan_res {
2711                                         pending_msg_events.push(events::MessageSendEvent::HandleError {
2712                                                 node_id: channel.get_their_node_id(),
2713                                                 action: Some(msgs::ErrorAction::SendErrorMessage { msg: e }),
2714                                         });
2715                                         return false;
2716                                 }
2717                                 if let Some(funding_txo) = channel.get_funding_txo() {
2718                                         for tx in txn_matched {
2719                                                 for inp in tx.input.iter() {
2720                                                         if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
2721                                                                 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()));
2722                                                                 if let Some(short_id) = channel.get_short_channel_id() {
2723                                                                         short_to_id.remove(&short_id);
2724                                                                 }
2725                                                                 // It looks like our counterparty went on-chain. We go ahead and
2726                                                                 // broadcast our latest local state as well here, just in case its
2727                                                                 // some kind of SPV attack, though we expect these to be dropped.
2728                                                                 failed_channels.push(channel.force_shutdown());
2729                                                                 if let Ok(update) = self.get_channel_update(&channel) {
2730                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2731                                                                                 msg: update
2732                                                                         });
2733                                                                 }
2734                                                                 return false;
2735                                                         }
2736                                                 }
2737                                         }
2738                                 }
2739                                 if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height) {
2740                                         if let Some(short_id) = channel.get_short_channel_id() {
2741                                                 short_to_id.remove(&short_id);
2742                                         }
2743                                         failed_channels.push(channel.force_shutdown());
2744                                         // If would_broadcast_at_height() is true, the channel_monitor will broadcast
2745                                         // the latest local tx for us, so we should skip that here (it doesn't really
2746                                         // hurt anything, but does make tests a bit simpler).
2747                                         failed_channels.last_mut().unwrap().0 = Vec::new();
2748                                         if let Ok(update) = self.get_channel_update(&channel) {
2749                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2750                                                         msg: update
2751                                                 });
2752                                         }
2753                                         return false;
2754                                 }
2755                                 true
2756                         });
2757                 }
2758                 for failure in failed_channels.drain(..) {
2759                         self.finish_force_close_channel(failure);
2760                 }
2761                 self.latest_block_height.store(height as usize, Ordering::Release);
2762                 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header_hash;
2763         }
2764
2765         /// We force-close the channel without letting our counterparty participate in the shutdown
2766         fn block_disconnected(&self, header: &BlockHeader) {
2767                 let _ = self.total_consistency_lock.read().unwrap();
2768                 let mut failed_channels = Vec::new();
2769                 {
2770                         let mut channel_lock = self.channel_state.lock().unwrap();
2771                         let channel_state = channel_lock.borrow_parts();
2772                         let short_to_id = channel_state.short_to_id;
2773                         let pending_msg_events = channel_state.pending_msg_events;
2774                         channel_state.by_id.retain(|_,  v| {
2775                                 if v.block_disconnected(header) {
2776                                         if let Some(short_id) = v.get_short_channel_id() {
2777                                                 short_to_id.remove(&short_id);
2778                                         }
2779                                         failed_channels.push(v.force_shutdown());
2780                                         if let Ok(update) = self.get_channel_update(&v) {
2781                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2782                                                         msg: update
2783                                                 });
2784                                         }
2785                                         false
2786                                 } else {
2787                                         true
2788                                 }
2789                         });
2790                 }
2791                 for failure in failed_channels.drain(..) {
2792                         self.finish_force_close_channel(failure);
2793                 }
2794                 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
2795                 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
2796         }
2797 }
2798
2799 impl ChannelMessageHandler for ChannelManager {
2800         //TODO: Handle errors and close channel (or so)
2801         fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), HandleError> {
2802                 let _ = self.total_consistency_lock.read().unwrap();
2803                 handle_error!(self, self.internal_open_channel(their_node_id, msg), their_node_id)
2804         }
2805
2806         fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), HandleError> {
2807                 let _ = self.total_consistency_lock.read().unwrap();
2808                 handle_error!(self, self.internal_accept_channel(their_node_id, msg), their_node_id)
2809         }
2810
2811         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), HandleError> {
2812                 let _ = self.total_consistency_lock.read().unwrap();
2813                 handle_error!(self, self.internal_funding_created(their_node_id, msg), their_node_id)
2814         }
2815
2816         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), HandleError> {
2817                 let _ = self.total_consistency_lock.read().unwrap();
2818                 handle_error!(self, self.internal_funding_signed(their_node_id, msg), their_node_id)
2819         }
2820
2821         fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), HandleError> {
2822                 let _ = self.total_consistency_lock.read().unwrap();
2823                 handle_error!(self, self.internal_funding_locked(their_node_id, msg), their_node_id)
2824         }
2825
2826         fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), HandleError> {
2827                 let _ = self.total_consistency_lock.read().unwrap();
2828                 handle_error!(self, self.internal_shutdown(their_node_id, msg), their_node_id)
2829         }
2830
2831         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), HandleError> {
2832                 let _ = self.total_consistency_lock.read().unwrap();
2833                 handle_error!(self, self.internal_closing_signed(their_node_id, msg), their_node_id)
2834         }
2835
2836         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), msgs::HandleError> {
2837                 let _ = self.total_consistency_lock.read().unwrap();
2838                 handle_error!(self, self.internal_update_add_htlc(their_node_id, msg), their_node_id)
2839         }
2840
2841         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), HandleError> {
2842                 let _ = self.total_consistency_lock.read().unwrap();
2843                 handle_error!(self, self.internal_update_fulfill_htlc(their_node_id, msg), their_node_id)
2844         }
2845
2846         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), HandleError> {
2847                 let _ = self.total_consistency_lock.read().unwrap();
2848                 handle_error!(self, self.internal_update_fail_htlc(their_node_id, msg), their_node_id)
2849         }
2850
2851         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), HandleError> {
2852                 let _ = self.total_consistency_lock.read().unwrap();
2853                 handle_error!(self, self.internal_update_fail_malformed_htlc(their_node_id, msg), their_node_id)
2854         }
2855
2856         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), HandleError> {
2857                 let _ = self.total_consistency_lock.read().unwrap();
2858                 handle_error!(self, self.internal_commitment_signed(their_node_id, msg), their_node_id)
2859         }
2860
2861         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), HandleError> {
2862                 let _ = self.total_consistency_lock.read().unwrap();
2863                 handle_error!(self, self.internal_revoke_and_ack(their_node_id, msg), their_node_id)
2864         }
2865
2866         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), HandleError> {
2867                 let _ = self.total_consistency_lock.read().unwrap();
2868                 handle_error!(self, self.internal_update_fee(their_node_id, msg), their_node_id)
2869         }
2870
2871         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), HandleError> {
2872                 let _ = self.total_consistency_lock.read().unwrap();
2873                 handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
2874         }
2875
2876         fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), HandleError> {
2877                 let _ = self.total_consistency_lock.read().unwrap();
2878                 handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), their_node_id)
2879         }
2880
2881         fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
2882                 let _ = self.total_consistency_lock.read().unwrap();
2883                 let mut failed_channels = Vec::new();
2884                 let mut failed_payments = Vec::new();
2885                 {
2886                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2887                         let channel_state = channel_state_lock.borrow_parts();
2888                         let short_to_id = channel_state.short_to_id;
2889                         let pending_msg_events = channel_state.pending_msg_events;
2890                         if no_connection_possible {
2891                                 log_debug!(self, "Failing all channels with {} due to no_connection_possible", log_pubkey!(their_node_id));
2892                                 channel_state.by_id.retain(|_, chan| {
2893                                         if chan.get_their_node_id() == *their_node_id {
2894                                                 if let Some(short_id) = chan.get_short_channel_id() {
2895                                                         short_to_id.remove(&short_id);
2896                                                 }
2897                                                 failed_channels.push(chan.force_shutdown());
2898                                                 if let Ok(update) = self.get_channel_update(&chan) {
2899                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2900                                                                 msg: update
2901                                                         });
2902                                                 }
2903                                                 false
2904                                         } else {
2905                                                 true
2906                                         }
2907                                 });
2908                         } else {
2909                                 log_debug!(self, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(their_node_id));
2910                                 channel_state.by_id.retain(|_, chan| {
2911                                         if chan.get_their_node_id() == *their_node_id {
2912                                                 //TODO: mark channel disabled (and maybe announce such after a timeout).
2913                                                 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused();
2914                                                 if !failed_adds.is_empty() {
2915                                                         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
2916                                                         failed_payments.push((chan_update, failed_adds));
2917                                                 }
2918                                                 if chan.is_shutdown() {
2919                                                         if let Some(short_id) = chan.get_short_channel_id() {
2920                                                                 short_to_id.remove(&short_id);
2921                                                         }
2922                                                         return false;
2923                                                 }
2924                                         }
2925                                         true
2926                                 })
2927                         }
2928                 }
2929                 for failure in failed_channels.drain(..) {
2930                         self.finish_force_close_channel(failure);
2931                 }
2932                 for (chan_update, mut htlc_sources) in failed_payments {
2933                         for (htlc_source, payment_hash) in htlc_sources.drain(..) {
2934                                 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
2935                         }
2936                 }
2937         }
2938
2939         fn peer_connected(&self, their_node_id: &PublicKey) {
2940                 log_debug!(self, "Generating channel_reestablish events for {}", log_pubkey!(their_node_id));
2941
2942                 let _ = self.total_consistency_lock.read().unwrap();
2943                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2944                 let channel_state = channel_state_lock.borrow_parts();
2945                 let pending_msg_events = channel_state.pending_msg_events;
2946                 channel_state.by_id.retain(|_, chan| {
2947                         if chan.get_their_node_id() == *their_node_id {
2948                                 if !chan.have_received_message() {
2949                                         // If we created this (outbound) channel while we were disconnected from the
2950                                         // peer we probably failed to send the open_channel message, which is now
2951                                         // lost. We can't have had anything pending related to this channel, so we just
2952                                         // drop it.
2953                                         false
2954                                 } else {
2955                                         pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
2956                                                 node_id: chan.get_their_node_id(),
2957                                                 msg: chan.get_channel_reestablish(),
2958                                         });
2959                                         true
2960                                 }
2961                         } else { true }
2962                 });
2963                 //TODO: Also re-broadcast announcement_signatures
2964         }
2965
2966         fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
2967                 let _ = self.total_consistency_lock.read().unwrap();
2968
2969                 if msg.channel_id == [0; 32] {
2970                         for chan in self.list_channels() {
2971                                 if chan.remote_network_id == *their_node_id {
2972                                         self.force_close_channel(&chan.channel_id);
2973                                 }
2974                         }
2975                 } else {
2976                         self.force_close_channel(&msg.channel_id);
2977                 }
2978         }
2979 }
2980
2981 const SERIALIZATION_VERSION: u8 = 1;
2982 const MIN_SERIALIZATION_VERSION: u8 = 1;
2983
2984 impl Writeable for PendingForwardHTLCInfo {
2985         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2986                 if let &Some(ref onion) = &self.onion_packet {
2987                         1u8.write(writer)?;
2988                         onion.write(writer)?;
2989                 } else {
2990                         0u8.write(writer)?;
2991                 }
2992                 self.incoming_shared_secret.write(writer)?;
2993                 self.payment_hash.write(writer)?;
2994                 self.short_channel_id.write(writer)?;
2995                 self.amt_to_forward.write(writer)?;
2996                 self.outgoing_cltv_value.write(writer)?;
2997                 Ok(())
2998         }
2999 }
3000
3001 impl<R: ::std::io::Read> Readable<R> for PendingForwardHTLCInfo {
3002         fn read(reader: &mut R) -> Result<PendingForwardHTLCInfo, DecodeError> {
3003                 let onion_packet = match <u8 as Readable<R>>::read(reader)? {
3004                         0 => None,
3005                         1 => Some(msgs::OnionPacket::read(reader)?),
3006                         _ => return Err(DecodeError::InvalidValue),
3007                 };
3008                 Ok(PendingForwardHTLCInfo {
3009                         onion_packet,
3010                         incoming_shared_secret: Readable::read(reader)?,
3011                         payment_hash: Readable::read(reader)?,
3012                         short_channel_id: Readable::read(reader)?,
3013                         amt_to_forward: Readable::read(reader)?,
3014                         outgoing_cltv_value: Readable::read(reader)?,
3015                 })
3016         }
3017 }
3018
3019 impl Writeable for HTLCFailureMsg {
3020         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3021                 match self {
3022                         &HTLCFailureMsg::Relay(ref fail_msg) => {
3023                                 0u8.write(writer)?;
3024                                 fail_msg.write(writer)?;
3025                         },
3026                         &HTLCFailureMsg::Malformed(ref fail_msg) => {
3027                                 1u8.write(writer)?;
3028                                 fail_msg.write(writer)?;
3029                         }
3030                 }
3031                 Ok(())
3032         }
3033 }
3034
3035 impl<R: ::std::io::Read> Readable<R> for HTLCFailureMsg {
3036         fn read(reader: &mut R) -> Result<HTLCFailureMsg, DecodeError> {
3037                 match <u8 as Readable<R>>::read(reader)? {
3038                         0 => Ok(HTLCFailureMsg::Relay(Readable::read(reader)?)),
3039                         1 => Ok(HTLCFailureMsg::Malformed(Readable::read(reader)?)),
3040                         _ => Err(DecodeError::InvalidValue),
3041                 }
3042         }
3043 }
3044
3045 impl Writeable for PendingHTLCStatus {
3046         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3047                 match self {
3048                         &PendingHTLCStatus::Forward(ref forward_info) => {
3049                                 0u8.write(writer)?;
3050                                 forward_info.write(writer)?;
3051                         },
3052                         &PendingHTLCStatus::Fail(ref fail_msg) => {
3053                                 1u8.write(writer)?;
3054                                 fail_msg.write(writer)?;
3055                         }
3056                 }
3057                 Ok(())
3058         }
3059 }
3060
3061 impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
3062         fn read(reader: &mut R) -> Result<PendingHTLCStatus, DecodeError> {
3063                 match <u8 as Readable<R>>::read(reader)? {
3064                         0 => Ok(PendingHTLCStatus::Forward(Readable::read(reader)?)),
3065                         1 => Ok(PendingHTLCStatus::Fail(Readable::read(reader)?)),
3066                         _ => Err(DecodeError::InvalidValue),
3067                 }
3068         }
3069 }
3070
3071 impl_writeable!(HTLCPreviousHopData, 0, {
3072         short_channel_id,
3073         htlc_id,
3074         incoming_packet_shared_secret
3075 });
3076
3077 impl Writeable for HTLCSource {
3078         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3079                 match self {
3080                         &HTLCSource::PreviousHopData(ref hop_data) => {
3081                                 0u8.write(writer)?;
3082                                 hop_data.write(writer)?;
3083                         },
3084                         &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } => {
3085                                 1u8.write(writer)?;
3086                                 route.write(writer)?;
3087                                 session_priv.write(writer)?;
3088                                 first_hop_htlc_msat.write(writer)?;
3089                         }
3090                 }
3091                 Ok(())
3092         }
3093 }
3094
3095 impl<R: ::std::io::Read> Readable<R> for HTLCSource {
3096         fn read(reader: &mut R) -> Result<HTLCSource, DecodeError> {
3097                 match <u8 as Readable<R>>::read(reader)? {
3098                         0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
3099                         1 => Ok(HTLCSource::OutboundRoute {
3100                                 route: Readable::read(reader)?,
3101                                 session_priv: Readable::read(reader)?,
3102                                 first_hop_htlc_msat: Readable::read(reader)?,
3103                         }),
3104                         _ => Err(DecodeError::InvalidValue),
3105                 }
3106         }
3107 }
3108
3109 impl Writeable for HTLCFailReason {
3110         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3111                 match self {
3112                         &HTLCFailReason::ErrorPacket { ref err } => {
3113                                 0u8.write(writer)?;
3114                                 err.write(writer)?;
3115                         },
3116                         &HTLCFailReason::Reason { ref failure_code, ref data } => {
3117                                 1u8.write(writer)?;
3118                                 failure_code.write(writer)?;
3119                                 data.write(writer)?;
3120                         }
3121                 }
3122                 Ok(())
3123         }
3124 }
3125
3126 impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
3127         fn read(reader: &mut R) -> Result<HTLCFailReason, DecodeError> {
3128                 match <u8 as Readable<R>>::read(reader)? {
3129                         0 => Ok(HTLCFailReason::ErrorPacket { err: Readable::read(reader)? }),
3130                         1 => Ok(HTLCFailReason::Reason {
3131                                 failure_code: Readable::read(reader)?,
3132                                 data: Readable::read(reader)?,
3133                         }),
3134                         _ => Err(DecodeError::InvalidValue),
3135                 }
3136         }
3137 }
3138
3139 impl_writeable!(HTLCForwardInfo, 0, {
3140         prev_short_channel_id,
3141         prev_htlc_id,
3142         forward_info
3143 });
3144
3145 impl Writeable for ChannelManager {
3146         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3147                 let _ = self.total_consistency_lock.write().unwrap();
3148
3149                 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
3150                 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
3151
3152                 self.genesis_hash.write(writer)?;
3153                 (self.latest_block_height.load(Ordering::Acquire) as u32).write(writer)?;
3154                 self.last_block_hash.lock().unwrap().write(writer)?;
3155
3156                 let channel_state = self.channel_state.lock().unwrap();
3157                 let mut unfunded_channels = 0;
3158                 for (_, channel) in channel_state.by_id.iter() {
3159                         if !channel.is_funding_initiated() {
3160                                 unfunded_channels += 1;
3161                         }
3162                 }
3163                 ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
3164                 for (_, channel) in channel_state.by_id.iter() {
3165                         if channel.is_funding_initiated() {
3166                                 channel.write(writer)?;
3167                         }
3168                 }
3169
3170                 (channel_state.forward_htlcs.len() as u64).write(writer)?;
3171                 for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
3172                         short_channel_id.write(writer)?;
3173                         (pending_forwards.len() as u64).write(writer)?;
3174                         for forward in pending_forwards {
3175                                 forward.write(writer)?;
3176                         }
3177                 }
3178
3179                 (channel_state.claimable_htlcs.len() as u64).write(writer)?;
3180                 for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
3181                         payment_hash.write(writer)?;
3182                         (previous_hops.len() as u64).write(writer)?;
3183                         for previous_hop in previous_hops {
3184                                 previous_hop.write(writer)?;
3185                         }
3186                 }
3187
3188                 Ok(())
3189         }
3190 }
3191
3192 /// Arguments for the creation of a ChannelManager that are not deserialized.
3193 ///
3194 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
3195 /// is:
3196 /// 1) Deserialize all stored ChannelMonitors.
3197 /// 2) Deserialize the ChannelManager by filling in this struct and calling <(Sha256dHash,
3198 ///    ChannelManager)>::read(reader, args).
3199 ///    This may result in closing some Channels if the ChannelMonitor is newer than the stored
3200 ///    ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
3201 /// 3) Register all relevant ChannelMonitor outpoints with your chain watch mechanism using
3202 ///    ChannelMonitor::get_monitored_outpoints and ChannelMonitor::get_funding_txo().
3203 /// 4) Reconnect blocks on your ChannelMonitors.
3204 /// 5) Move the ChannelMonitors into your local ManyChannelMonitor.
3205 /// 6) Disconnect/connect blocks on the ChannelManager.
3206 /// 7) Register the new ChannelManager with your ChainWatchInterface (this does not happen
3207 ///    automatically as it does in ChannelManager::new()).
3208 pub struct ChannelManagerReadArgs<'a> {
3209         /// The keys provider which will give us relevant keys. Some keys will be loaded during
3210         /// deserialization.
3211         pub keys_manager: Arc<KeysInterface>,
3212
3213         /// The fee_estimator for use in the ChannelManager in the future.
3214         ///
3215         /// No calls to the FeeEstimator will be made during deserialization.
3216         pub fee_estimator: Arc<FeeEstimator>,
3217         /// The ManyChannelMonitor for use in the ChannelManager in the future.
3218         ///
3219         /// No calls to the ManyChannelMonitor will be made during deserialization. It is assumed that
3220         /// you have deserialized ChannelMonitors separately and will add them to your
3221         /// ManyChannelMonitor after deserializing this ChannelManager.
3222         pub monitor: Arc<ManyChannelMonitor>,
3223         /// The ChainWatchInterface for use in the ChannelManager in the future.
3224         ///
3225         /// No calls to the ChainWatchInterface will be made during deserialization.
3226         pub chain_monitor: Arc<ChainWatchInterface>,
3227         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
3228         /// used to broadcast the latest local commitment transactions of channels which must be
3229         /// force-closed during deserialization.
3230         pub tx_broadcaster: Arc<BroadcasterInterface>,
3231         /// The Logger for use in the ChannelManager and which may be used to log information during
3232         /// deserialization.
3233         pub logger: Arc<Logger>,
3234         /// Default settings used for new channels. Any existing channels will continue to use the
3235         /// runtime settings which were stored when the ChannelManager was serialized.
3236         pub default_config: UserConfig,
3237
3238         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
3239         /// value.get_funding_txo() should be the key).
3240         ///
3241         /// If a monitor is inconsistent with the channel state during deserialization the channel will
3242         /// be force-closed using the data in the channelmonitor and the Channel will be dropped. This
3243         /// is true for missing channels as well. If there is a monitor missing for which we find
3244         /// channel data Err(DecodeError::InvalidValue) will be returned.
3245         ///
3246         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
3247         /// this struct.
3248         pub channel_monitors: &'a HashMap<OutPoint, &'a ChannelMonitor>,
3249 }
3250
3251 impl<'a, R : ::std::io::Read> ReadableArgs<R, ChannelManagerReadArgs<'a>> for (Sha256dHash, ChannelManager) {
3252         fn read(reader: &mut R, args: ChannelManagerReadArgs<'a>) -> Result<Self, DecodeError> {
3253                 let _ver: u8 = Readable::read(reader)?;
3254                 let min_ver: u8 = Readable::read(reader)?;
3255                 if min_ver > SERIALIZATION_VERSION {
3256                         return Err(DecodeError::UnknownVersion);
3257                 }
3258
3259                 let genesis_hash: Sha256dHash = Readable::read(reader)?;
3260                 let latest_block_height: u32 = Readable::read(reader)?;
3261                 let last_block_hash: Sha256dHash = Readable::read(reader)?;
3262
3263                 let mut closed_channels = Vec::new();
3264
3265                 let channel_count: u64 = Readable::read(reader)?;
3266                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
3267                 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3268                 let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3269                 for _ in 0..channel_count {
3270                         let mut channel: Channel = ReadableArgs::read(reader, args.logger.clone())?;
3271                         if channel.last_block_connected != last_block_hash {
3272                                 return Err(DecodeError::InvalidValue);
3273                         }
3274
3275                         let funding_txo = channel.channel_monitor().get_funding_txo().ok_or(DecodeError::InvalidValue)?;
3276                         funding_txo_set.insert(funding_txo.clone());
3277                         if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
3278                                 if channel.get_cur_local_commitment_transaction_number() != monitor.get_cur_local_commitment_number() ||
3279                                                 channel.get_revoked_remote_commitment_transaction_number() != monitor.get_min_seen_secret() ||
3280                                                 channel.get_cur_remote_commitment_transaction_number() != monitor.get_cur_remote_commitment_number() {
3281                                         let mut force_close_res = channel.force_shutdown();
3282                                         force_close_res.0 = monitor.get_latest_local_commitment_txn();
3283                                         closed_channels.push(force_close_res);
3284                                 } else {
3285                                         if let Some(short_channel_id) = channel.get_short_channel_id() {
3286                                                 short_to_id.insert(short_channel_id, channel.channel_id());
3287                                         }
3288                                         by_id.insert(channel.channel_id(), channel);
3289                                 }
3290                         } else {
3291                                 return Err(DecodeError::InvalidValue);
3292                         }
3293                 }
3294
3295                 for (ref funding_txo, ref monitor) in args.channel_monitors.iter() {
3296                         if !funding_txo_set.contains(funding_txo) {
3297                                 closed_channels.push((monitor.get_latest_local_commitment_txn(), Vec::new()));
3298                         }
3299                 }
3300
3301                 let forward_htlcs_count: u64 = Readable::read(reader)?;
3302                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
3303                 for _ in 0..forward_htlcs_count {
3304                         let short_channel_id = Readable::read(reader)?;
3305                         let pending_forwards_count: u64 = Readable::read(reader)?;
3306                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, 128));
3307                         for _ in 0..pending_forwards_count {
3308                                 pending_forwards.push(Readable::read(reader)?);
3309                         }
3310                         forward_htlcs.insert(short_channel_id, pending_forwards);
3311                 }
3312
3313                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
3314                 let mut claimable_htlcs = HashMap::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
3315                 for _ in 0..claimable_htlcs_count {
3316                         let payment_hash = Readable::read(reader)?;
3317                         let previous_hops_len: u64 = Readable::read(reader)?;
3318                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, 2));
3319                         for _ in 0..previous_hops_len {
3320                                 previous_hops.push(Readable::read(reader)?);
3321                         }
3322                         claimable_htlcs.insert(payment_hash, previous_hops);
3323                 }
3324
3325                 let channel_manager = ChannelManager {
3326                         genesis_hash,
3327                         fee_estimator: args.fee_estimator,
3328                         monitor: args.monitor,
3329                         chain_monitor: args.chain_monitor,
3330                         tx_broadcaster: args.tx_broadcaster,
3331
3332                         latest_block_height: AtomicUsize::new(latest_block_height as usize),
3333                         last_block_hash: Mutex::new(last_block_hash),
3334                         secp_ctx: Secp256k1::new(),
3335
3336                         channel_state: Mutex::new(ChannelHolder {
3337                                 by_id,
3338                                 short_to_id,
3339                                 next_forward: Instant::now(),
3340                                 forward_htlcs,
3341                                 claimable_htlcs,
3342                                 pending_msg_events: Vec::new(),
3343                         }),
3344                         our_network_key: args.keys_manager.get_node_secret(),
3345
3346                         pending_events: Mutex::new(Vec::new()),
3347                         total_consistency_lock: RwLock::new(()),
3348                         keys_manager: args.keys_manager,
3349                         logger: args.logger,
3350                         default_configuration: args.default_config,
3351                 };
3352
3353                 for close_res in closed_channels.drain(..) {
3354                         channel_manager.finish_force_close_channel(close_res);
3355                         //TODO: Broadcast channel update for closed channels, but only after we've made a
3356                         //connection or two.
3357                 }
3358
3359                 Ok((last_block_hash.clone(), channel_manager))
3360         }
3361 }
3362
3363 #[cfg(test)]
3364 mod tests {
3365         use chain::chaininterface;
3366         use chain::transaction::OutPoint;
3367         use chain::chaininterface::{ChainListener, ChainWatchInterface};
3368         use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor};
3369         use chain::keysinterface;
3370         use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
3371         use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,OnionKeys,PaymentFailReason,RAACommitmentOrder, PaymentPreimage, PaymentHash};
3372         use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, ManyChannelMonitor};
3373         use ln::channel::{ACCEPTED_HTLC_SCRIPT_WEIGHT, OFFERED_HTLC_SCRIPT_WEIGHT};
3374         use ln::router::{Route, RouteHop, Router};
3375         use ln::msgs;
3376         use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler};
3377         use util::test_utils;
3378         use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
3379         use util::errors::APIError;
3380         use util::logger::Logger;
3381         use util::ser::{Writeable, Writer, ReadableArgs};
3382         use util::config::UserConfig;
3383
3384         use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
3385         use bitcoin::util::bip143;
3386         use bitcoin::util::address::Address;
3387         use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
3388         use bitcoin::blockdata::block::{Block, BlockHeader};
3389         use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType};
3390         use bitcoin::blockdata::script::{Builder, Script};
3391         use bitcoin::blockdata::opcodes;
3392         use bitcoin::blockdata::constants::genesis_block;
3393         use bitcoin::network::constants::Network;
3394
3395         use hex;
3396
3397         use secp256k1::{Secp256k1, Message};
3398         use secp256k1::key::{PublicKey,SecretKey};
3399
3400         use crypto::sha2::Sha256;
3401         use crypto::digest::Digest;
3402
3403         use rand::{thread_rng,Rng};
3404
3405         use std::cell::RefCell;
3406         use std::collections::{BTreeSet, HashMap, HashSet};
3407         use std::default::Default;
3408         use std::rc::Rc;
3409         use std::sync::{Arc, Mutex};
3410         use std::sync::atomic::Ordering;
3411         use std::time::Instant;
3412         use std::mem;
3413
3414         fn build_test_onion_keys() -> Vec<OnionKeys> {
3415                 // Keys from BOLT 4, used in both test vector tests
3416                 let secp_ctx = Secp256k1::new();
3417
3418                 let route = Route {
3419                         hops: vec!(
3420                                         RouteHop {
3421                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
3422                                                 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
3423                                         },
3424                                         RouteHop {
3425                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
3426                                                 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
3427                                         },
3428                                         RouteHop {
3429                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").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("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").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("02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145").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                         ),
3441                 };
3442
3443                 let session_priv = SecretKey::from_slice(&secp_ctx, &hex::decode("4141414141414141414141414141414141414141414141414141414141414141").unwrap()[..]).unwrap();
3444
3445                 let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
3446                 assert_eq!(onion_keys.len(), route.hops.len());
3447                 onion_keys
3448         }
3449
3450         #[test]
3451         fn onion_vectors() {
3452                 // Packet creation test vectors from BOLT 4
3453                 let onion_keys = build_test_onion_keys();
3454
3455                 assert_eq!(onion_keys[0].shared_secret[..], hex::decode("53eb63ea8a3fec3b3cd433b85cd62a4b145e1dda09391b348c4e1cd36a03ea66").unwrap()[..]);
3456                 assert_eq!(onion_keys[0].blinding_factor[..], hex::decode("2ec2e5da605776054187180343287683aa6a51b4b1c04d6dd49c45d8cffb3c36").unwrap()[..]);
3457                 assert_eq!(onion_keys[0].ephemeral_pubkey.serialize()[..], hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]);
3458                 assert_eq!(onion_keys[0].rho, hex::decode("ce496ec94def95aadd4bec15cdb41a740c9f2b62347c4917325fcc6fb0453986").unwrap()[..]);
3459                 assert_eq!(onion_keys[0].mu, hex::decode("b57061dc6d0a2b9f261ac410c8b26d64ac5506cbba30267a649c28c179400eba").unwrap()[..]);
3460
3461                 assert_eq!(onion_keys[1].shared_secret[..], hex::decode("a6519e98832a0b179f62123b3567c106db99ee37bef036e783263602f3488fae").unwrap()[..]);
3462                 assert_eq!(onion_keys[1].blinding_factor[..], hex::decode("bf66c28bc22e598cfd574a1931a2bafbca09163df2261e6d0056b2610dab938f").unwrap()[..]);
3463                 assert_eq!(onion_keys[1].ephemeral_pubkey.serialize()[..], hex::decode("028f9438bfbf7feac2e108d677e3a82da596be706cc1cf342b75c7b7e22bf4e6e2").unwrap()[..]);
3464                 assert_eq!(onion_keys[1].rho, hex::decode("450ffcabc6449094918ebe13d4f03e433d20a3d28a768203337bc40b6e4b2c59").unwrap()[..]);
3465                 assert_eq!(onion_keys[1].mu, hex::decode("05ed2b4a3fb023c2ff5dd6ed4b9b6ea7383f5cfe9d59c11d121ec2c81ca2eea9").unwrap()[..]);
3466
3467                 assert_eq!(onion_keys[2].shared_secret[..], hex::decode("3a6b412548762f0dbccce5c7ae7bb8147d1caf9b5471c34120b30bc9c04891cc").unwrap()[..]);
3468                 assert_eq!(onion_keys[2].blinding_factor[..], hex::decode("a1f2dadd184eb1627049673f18c6325814384facdee5bfd935d9cb031a1698a5").unwrap()[..]);
3469                 assert_eq!(onion_keys[2].ephemeral_pubkey.serialize()[..], hex::decode("03bfd8225241ea71cd0843db7709f4c222f62ff2d4516fd38b39914ab6b83e0da0").unwrap()[..]);
3470                 assert_eq!(onion_keys[2].rho, hex::decode("11bf5c4f960239cb37833936aa3d02cea82c0f39fd35f566109c41f9eac8deea").unwrap()[..]);
3471                 assert_eq!(onion_keys[2].mu, hex::decode("caafe2820fa00eb2eeb78695ae452eba38f5a53ed6d53518c5c6edf76f3f5b78").unwrap()[..]);
3472
3473                 assert_eq!(onion_keys[3].shared_secret[..], hex::decode("21e13c2d7cfe7e18836df50872466117a295783ab8aab0e7ecc8c725503ad02d").unwrap()[..]);
3474                 assert_eq!(onion_keys[3].blinding_factor[..], hex::decode("7cfe0b699f35525029ae0fa437c69d0f20f7ed4e3916133f9cacbb13c82ff262").unwrap()[..]);
3475                 assert_eq!(onion_keys[3].ephemeral_pubkey.serialize()[..], hex::decode("031dde6926381289671300239ea8e57ffaf9bebd05b9a5b95beaf07af05cd43595").unwrap()[..]);
3476                 assert_eq!(onion_keys[3].rho, hex::decode("cbe784ab745c13ff5cffc2fbe3e84424aa0fd669b8ead4ee562901a4a4e89e9e").unwrap()[..]);
3477                 assert_eq!(onion_keys[3].mu, hex::decode("5052aa1b3d9f0655a0932e50d42f0c9ba0705142c25d225515c45f47c0036ee9").unwrap()[..]);
3478
3479                 assert_eq!(onion_keys[4].shared_secret[..], hex::decode("b5756b9b542727dbafc6765a49488b023a725d631af688fc031217e90770c328").unwrap()[..]);
3480                 assert_eq!(onion_keys[4].blinding_factor[..], hex::decode("c96e00dddaf57e7edcd4fb5954be5b65b09f17cb6d20651b4e90315be5779205").unwrap()[..]);
3481                 assert_eq!(onion_keys[4].ephemeral_pubkey.serialize()[..], hex::decode("03a214ebd875aab6ddfd77f22c5e7311d7f77f17a169e599f157bbcdae8bf071f4").unwrap()[..]);
3482                 assert_eq!(onion_keys[4].rho, hex::decode("034e18b8cc718e8af6339106e706c52d8df89e2b1f7e9142d996acf88df8799b").unwrap()[..]);
3483                 assert_eq!(onion_keys[4].mu, hex::decode("8e45e5c61c2b24cb6382444db6698727afb063adecd72aada233d4bf273d975a").unwrap()[..]);
3484
3485                 // Test vectors below are flat-out wrong: they claim to set outgoing_cltv_value to non-0 :/
3486                 let payloads = vec!(
3487                         msgs::OnionHopData {
3488                                 realm: 0,
3489                                 data: msgs::OnionRealm0HopData {
3490                                         short_channel_id: 0,
3491                                         amt_to_forward: 0,
3492                                         outgoing_cltv_value: 0,
3493                                 },
3494                                 hmac: [0; 32],
3495                         },
3496                         msgs::OnionHopData {
3497                                 realm: 0,
3498                                 data: msgs::OnionRealm0HopData {
3499                                         short_channel_id: 0x0101010101010101,
3500                                         amt_to_forward: 0x0100000001,
3501                                         outgoing_cltv_value: 0,
3502                                 },
3503                                 hmac: [0; 32],
3504                         },
3505                         msgs::OnionHopData {
3506                                 realm: 0,
3507                                 data: msgs::OnionRealm0HopData {
3508                                         short_channel_id: 0x0202020202020202,
3509                                         amt_to_forward: 0x0200000002,
3510                                         outgoing_cltv_value: 0,
3511                                 },
3512                                 hmac: [0; 32],
3513                         },
3514                         msgs::OnionHopData {
3515                                 realm: 0,
3516                                 data: msgs::OnionRealm0HopData {
3517                                         short_channel_id: 0x0303030303030303,
3518                                         amt_to_forward: 0x0300000003,
3519                                         outgoing_cltv_value: 0,
3520                                 },
3521                                 hmac: [0; 32],
3522                         },
3523                         msgs::OnionHopData {
3524                                 realm: 0,
3525                                 data: msgs::OnionRealm0HopData {
3526                                         short_channel_id: 0x0404040404040404,
3527                                         amt_to_forward: 0x0400000004,
3528                                         outgoing_cltv_value: 0,
3529                                 },
3530                                 hmac: [0; 32],
3531                         },
3532                 );
3533
3534                 let packet = ChannelManager::construct_onion_packet(payloads, onion_keys, &PaymentHash([0x42; 32]));
3535                 // Just check the final packet encoding, as it includes all the per-hop vectors in it
3536                 // anyway...
3537                 assert_eq!(packet.encode(), hex::decode("0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619e5f14350c2a76fc232b5e46d421e9615471ab9e0bc887beff8c95fdb878f7b3a716a996c7845c93d90e4ecbb9bde4ece2f69425c99e4bc820e44485455f135edc0d10f7d61ab590531cf08000179a333a347f8b4072f216400406bdf3bf038659793d4a1fd7b246979e3150a0a4cb052c9ec69acf0f48c3d39cd55675fe717cb7d80ce721caad69320c3a469a202f1e468c67eaf7a7cd8226d0fd32f7b48084dca885d56047694762b67021713ca673929c163ec36e04e40ca8e1c6d17569419d3039d9a1ec866abe044a9ad635778b961fc0776dc832b3a451bd5d35072d2269cf9b040f6b7a7dad84fb114ed413b1426cb96ceaf83825665ed5a1d002c1687f92465b49ed4c7f0218ff8c6c7dd7221d589c65b3b9aaa71a41484b122846c7c7b57e02e679ea8469b70e14fe4f70fee4d87b910cf144be6fe48eef24da475c0b0bcc6565ae82cd3f4e3b24c76eaa5616c6111343306ab35c1fe5ca4a77c0e314ed7dba39d6f1e0de791719c241a939cc493bea2bae1c1e932679ea94d29084278513c77b899cc98059d06a27d171b0dbdf6bee13ddc4fc17a0c4d2827d488436b57baa167544138ca2e64a11b43ac8a06cd0c2fba2d4d900ed2d9205305e2d7383cc98dacb078133de5f6fb6bed2ef26ba92cea28aafc3b9948dd9ae5559e8bd6920b8cea462aa445ca6a95e0e7ba52961b181c79e73bd581821df2b10173727a810c92b83b5ba4a0403eb710d2ca10689a35bec6c3a708e9e92f7d78ff3c5d9989574b00c6736f84c199256e76e19e78f0c98a9d580b4a658c84fc8f2096c2fbea8f5f8c59d0fdacb3be2802ef802abbecb3aba4acaac69a0e965abd8981e9896b1f6ef9d60f7a164b371af869fd0e48073742825e9434fc54da837e120266d53302954843538ea7c6c3dbfb4ff3b2fdbe244437f2a153ccf7bdb4c92aa08102d4f3cff2ae5ef86fab4653595e6a5837fa2f3e29f27a9cde5966843fb847a4a61f1e76c281fe8bb2b0a181d096100db5a1a5ce7a910238251a43ca556712eaadea167fb4d7d75825e440f3ecd782036d7574df8bceacb397abefc5f5254d2722215c53ff54af8299aaaad642c6d72a14d27882d9bbd539e1cc7a527526ba89b8c037ad09120e98ab042d3e8652b31ae0e478516bfaf88efca9f3676ffe99d2819dcaeb7610a626695f53117665d267d3f7abebd6bbd6733f645c72c389f03855bdf1e4b8075b516569b118233a0f0971d24b83113c0b096f5216a207ca99a7cddc81c130923fe3d91e7508c9ac5f2e914ff5dccab9e558566fa14efb34ac98d878580814b94b73acbfde9072f30b881f7f0fff42d4045d1ace6322d86a97d164aa84d93a60498065cc7c20e636f5862dc81531a88c60305a2e59a985be327a6902e4bed986dbf4a0b50c217af0ea7fdf9ab37f9ea1a1aaa72f54cf40154ea9b269f1a7c09f9f43245109431a175d50e2db0132337baa0ef97eed0fcf20489da36b79a1172faccc2f7ded7c60e00694282d93359c4682135642bc81f433574aa8ef0c97b4ade7ca372c5ffc23c7eddd839bab4e0f14d6df15c9dbeab176bec8b5701cf054eb3072f6dadc98f88819042bf10c407516ee58bce33fbe3b3d86a54255e577db4598e30a135361528c101683a5fcde7e8ba53f3456254be8f45fe3a56120ae96ea3773631fcb3873aa3abd91bcff00bd38bd43697a2e789e00da6077482e7b1b1a677b5afae4c54e6cbdf7377b694eb7d7a5b913476a5be923322d3de06060fd5e819635232a2cf4f0731da13b8546d1d6d4f8d75b9fce6c2341a71b0ea6f780df54bfdb0dd5cd9855179f602f9172307c7268724c3618e6817abd793adc214a0dc0bc616816632f27ea336fb56dfd").unwrap());
3538         }
3539
3540         #[test]
3541         fn test_failure_packet_onion() {
3542                 // Returning Errors test vectors from BOLT 4
3543
3544                 let onion_keys = build_test_onion_keys();
3545                 let onion_error = ChannelManager::build_failure_packet(&onion_keys[4].shared_secret[..], 0x2002, &[0; 0]);
3546                 assert_eq!(onion_error.encode(), hex::decode("4c2fc8bc08510334b6833ad9c3e79cd1b52ae59dfe5c2a4b23ead50f09f7ee0b0002200200fe0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap());
3547
3548                 let onion_packet_1 = ChannelManager::encrypt_failure_packet(&onion_keys[4].shared_secret[..], &onion_error.encode()[..]);
3549                 assert_eq!(onion_packet_1.data, hex::decode("a5e6bd0c74cb347f10cce367f949098f2457d14c046fd8a22cb96efb30b0fdcda8cb9168b50f2fd45edd73c1b0c8b33002df376801ff58aaa94000bf8a86f92620f343baef38a580102395ae3abf9128d1047a0736ff9b83d456740ebbb4aeb3aa9737f18fb4afb4aa074fb26c4d702f42968888550a3bded8c05247e045b866baef0499f079fdaeef6538f31d44deafffdfd3afa2fb4ca9082b8f1c465371a9894dd8c243fb4847e004f5256b3e90e2edde4c9fb3082ddfe4d1e734cacd96ef0706bf63c9984e22dc98851bcccd1c3494351feb458c9c6af41c0044bea3c47552b1d992ae542b17a2d0bba1a096c78d169034ecb55b6e3a7263c26017f033031228833c1daefc0dedb8cf7c3e37c9c37ebfe42f3225c326e8bcfd338804c145b16e34e4").unwrap());
3550
3551                 let onion_packet_2 = ChannelManager::encrypt_failure_packet(&onion_keys[3].shared_secret[..], &onion_packet_1.data[..]);
3552                 assert_eq!(onion_packet_2.data, hex::decode("c49a1ce81680f78f5f2000cda36268de34a3f0a0662f55b4e837c83a8773c22aa081bab1616a0011585323930fa5b9fae0c85770a2279ff59ec427ad1bbff9001c0cd1497004bd2a0f68b50704cf6d6a4bf3c8b6a0833399a24b3456961ba00736785112594f65b6b2d44d9f5ea4e49b5e1ec2af978cbe31c67114440ac51a62081df0ed46d4a3df295da0b0fe25c0115019f03f15ec86fabb4c852f83449e812f141a9395b3f70b766ebbd4ec2fae2b6955bd8f32684c15abfe8fd3a6261e52650e8807a92158d9f1463261a925e4bfba44bd20b166d532f0017185c3a6ac7957adefe45559e3072c8dc35abeba835a8cb01a71a15c736911126f27d46a36168ca5ef7dccd4e2886212602b181463e0dd30185c96348f9743a02aca8ec27c0b90dca270").unwrap());
3553
3554                 let onion_packet_3 = ChannelManager::encrypt_failure_packet(&onion_keys[2].shared_secret[..], &onion_packet_2.data[..]);
3555                 assert_eq!(onion_packet_3.data, hex::decode("a5d3e8634cfe78b2307d87c6d90be6fe7855b4f2cc9b1dfb19e92e4b79103f61ff9ac25f412ddfb7466e74f81b3e545563cdd8f5524dae873de61d7bdfccd496af2584930d2b566b4f8d3881f8c043df92224f38cf094cfc09d92655989531524593ec6d6caec1863bdfaa79229b5020acc034cd6deeea1021c50586947b9b8e6faa83b81fbfa6133c0af5d6b07c017f7158fa94f0d206baf12dda6b68f785b773b360fd0497e16cc402d779c8d48d0fa6315536ef0660f3f4e1865f5b38ea49c7da4fd959de4e83ff3ab686f059a45c65ba2af4a6a79166aa0f496bf04d06987b6d2ea205bdb0d347718b9aeff5b61dfff344993a275b79717cd815b6ad4c0beb568c4ac9c36ff1c315ec1119a1993c4b61e6eaa0375e0aaf738ac691abd3263bf937e3").unwrap());
3556
3557                 let onion_packet_4 = ChannelManager::encrypt_failure_packet(&onion_keys[1].shared_secret[..], &onion_packet_3.data[..]);
3558                 assert_eq!(onion_packet_4.data, hex::decode("aac3200c4968f56b21f53e5e374e3a2383ad2b1b6501bbcc45abc31e59b26881b7dfadbb56ec8dae8857add94e6702fb4c3a4de22e2e669e1ed926b04447fc73034bb730f4932acd62727b75348a648a1128744657ca6a4e713b9b646c3ca66cac02cdab44dd3439890ef3aaf61708714f7375349b8da541b2548d452d84de7084bb95b3ac2345201d624d31f4d52078aa0fa05a88b4e20202bd2b86ac5b52919ea305a8949de95e935eed0319cf3cf19ebea61d76ba92532497fcdc9411d06bcd4275094d0a4a3c5d3a945e43305a5a9256e333e1f64dbca5fcd4e03a39b9012d197506e06f29339dfee3331995b21615337ae060233d39befea925cc262873e0530408e6990f1cbd233a150ef7b004ff6166c70c68d9f8c853c1abca640b8660db2921").unwrap());
3559
3560                 let onion_packet_5 = ChannelManager::encrypt_failure_packet(&onion_keys[0].shared_secret[..], &onion_packet_4.data[..]);
3561                 assert_eq!(onion_packet_5.data, hex::decode("9c5add3963fc7f6ed7f148623c84134b5647e1306419dbe2174e523fa9e2fbed3a06a19f899145610741c83ad40b7712aefaddec8c6baf7325d92ea4ca4d1df8bce517f7e54554608bf2bd8071a4f52a7a2f7ffbb1413edad81eeea5785aa9d990f2865dc23b4bc3c301a94eec4eabebca66be5cf638f693ec256aec514620cc28ee4a94bd9565bc4d4962b9d3641d4278fb319ed2b84de5b665f307a2db0f7fbb757366067d88c50f7e829138fde4f78d39b5b5802f1b92a8a820865af5cc79f9f30bc3f461c66af95d13e5e1f0381c184572a91dee1c849048a647a1158cf884064deddbf1b0b88dfe2f791428d0ba0f6fb2f04e14081f69165ae66d9297c118f0907705c9c4954a199bae0bb96fad763d690e7daa6cfda59ba7f2c8d11448b604d12d").unwrap());
3562         }
3563
3564         fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
3565                 assert!(chain.does_match_tx(tx));
3566                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3567                 chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
3568                 for i in 2..100 {
3569                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3570                         chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
3571                 }
3572         }
3573
3574         struct Node {
3575                 chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
3576                 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
3577                 chan_monitor: Arc<test_utils::TestChannelMonitor>,
3578                 node: Arc<ChannelManager>,
3579                 router: Router,
3580                 node_seed: [u8; 32],
3581                 network_payment_count: Rc<RefCell<u8>>,
3582                 network_chan_count: Rc<RefCell<u32>>,
3583         }
3584         impl Drop for Node {
3585                 fn drop(&mut self) {
3586                         if !::std::thread::panicking() {
3587                                 // Check that we processed all pending events
3588                                 assert_eq!(self.node.get_and_clear_pending_msg_events().len(), 0);
3589                                 assert_eq!(self.node.get_and_clear_pending_events().len(), 0);
3590                                 assert_eq!(self.chan_monitor.added_monitors.lock().unwrap().len(), 0);
3591                         }
3592                 }
3593         }
3594
3595         fn create_chan_between_nodes(node_a: &Node, node_b: &Node) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3596                 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001)
3597         }
3598
3599         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) {
3600                 let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat);
3601                 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
3602                 (announcement, as_update, bs_update, channel_id, tx)
3603         }
3604
3605         macro_rules! get_revoke_commit_msgs {
3606                 ($node: expr, $node_id: expr) => {
3607                         {
3608                                 let events = $node.node.get_and_clear_pending_msg_events();
3609                                 assert_eq!(events.len(), 2);
3610                                 (match events[0] {
3611                                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3612                                                 assert_eq!(*node_id, $node_id);
3613                                                 (*msg).clone()
3614                                         },
3615                                         _ => panic!("Unexpected event"),
3616                                 }, match events[1] {
3617                                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3618                                                 assert_eq!(*node_id, $node_id);
3619                                                 assert!(updates.update_add_htlcs.is_empty());
3620                                                 assert!(updates.update_fulfill_htlcs.is_empty());
3621                                                 assert!(updates.update_fail_htlcs.is_empty());
3622                                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
3623                                                 assert!(updates.update_fee.is_none());
3624                                                 updates.commitment_signed.clone()
3625                                         },
3626                                         _ => panic!("Unexpected event"),
3627                                 })
3628                         }
3629                 }
3630         }
3631
3632         macro_rules! get_event_msg {
3633                 ($node: expr, $event_type: path, $node_id: expr) => {
3634                         {
3635                                 let events = $node.node.get_and_clear_pending_msg_events();
3636                                 assert_eq!(events.len(), 1);
3637                                 match events[0] {
3638                                         $event_type { ref node_id, ref msg } => {
3639                                                 assert_eq!(*node_id, $node_id);
3640                                                 (*msg).clone()
3641                                         },
3642                                         _ => panic!("Unexpected event"),
3643                                 }
3644                         }
3645                 }
3646         }
3647
3648         macro_rules! get_htlc_update_msgs {
3649                 ($node: expr, $node_id: expr) => {
3650                         {
3651                                 let events = $node.node.get_and_clear_pending_msg_events();
3652                                 assert_eq!(events.len(), 1);
3653                                 match events[0] {
3654                                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3655                                                 assert_eq!(*node_id, $node_id);
3656                                                 (*updates).clone()
3657                                         },
3658                                         _ => panic!("Unexpected event"),
3659                                 }
3660                         }
3661                 }
3662         }
3663
3664         macro_rules! get_feerate {
3665                 ($node: expr, $channel_id: expr) => {
3666                         {
3667                                 let chan_lock = $node.node.channel_state.lock().unwrap();
3668                                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
3669                                 chan.get_feerate()
3670                         }
3671                 }
3672         }
3673
3674
3675         fn create_chan_between_nodes_with_value_init(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> Transaction {
3676                 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
3677                 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();
3678                 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();
3679
3680                 let chan_id = *node_a.network_chan_count.borrow();
3681                 let tx;
3682                 let funding_output;
3683
3684                 let events_2 = node_a.node.get_and_clear_pending_events();
3685                 assert_eq!(events_2.len(), 1);
3686                 match events_2[0] {
3687                         Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
3688                                 assert_eq!(*channel_value_satoshis, channel_value);
3689                                 assert_eq!(user_channel_id, 42);
3690
3691                                 tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
3692                                         value: *channel_value_satoshis, script_pubkey: output_script.clone(),
3693                                 }]};
3694                                 funding_output = OutPoint::new(tx.txid(), 0);
3695
3696                                 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
3697                                 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3698                                 assert_eq!(added_monitors.len(), 1);
3699                                 assert_eq!(added_monitors[0].0, funding_output);
3700                                 added_monitors.clear();
3701                         },
3702                         _ => panic!("Unexpected event"),
3703                 }
3704
3705                 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();
3706                 {
3707                         let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
3708                         assert_eq!(added_monitors.len(), 1);
3709                         assert_eq!(added_monitors[0].0, funding_output);
3710                         added_monitors.clear();
3711                 }
3712
3713                 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();
3714                 {
3715                         let mut added_monitors = node_a.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                 let events_4 = node_a.node.get_and_clear_pending_events();
3722                 assert_eq!(events_4.len(), 1);
3723                 match events_4[0] {
3724                         Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
3725                                 assert_eq!(user_channel_id, 42);
3726                                 assert_eq!(*funding_txo, funding_output);
3727                         },
3728                         _ => panic!("Unexpected event"),
3729                 };
3730
3731                 tx
3732         }
3733
3734         fn create_chan_between_nodes_with_value_confirm(node_a: &Node, node_b: &Node, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
3735                 confirm_transaction(&node_b.chain_monitor, &tx, tx.version);
3736                 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();
3737
3738                 let channel_id;
3739
3740                 confirm_transaction(&node_a.chain_monitor, &tx, tx.version);
3741                 let events_6 = node_a.node.get_and_clear_pending_msg_events();
3742                 assert_eq!(events_6.len(), 2);
3743                 ((match events_6[0] {
3744                         MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3745                                 channel_id = msg.channel_id.clone();
3746                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
3747                                 msg.clone()
3748                         },
3749                         _ => panic!("Unexpected event"),
3750                 }, match events_6[1] {
3751                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3752                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
3753                                 msg.clone()
3754                         },
3755                         _ => panic!("Unexpected event"),
3756                 }), channel_id)
3757         }
3758
3759         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) {
3760                 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat);
3761                 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
3762                 (msgs, chan_id, tx)
3763         }
3764
3765         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) {
3766                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0).unwrap();
3767                 let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
3768                 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1).unwrap();
3769
3770                 let events_7 = node_b.node.get_and_clear_pending_msg_events();
3771                 assert_eq!(events_7.len(), 1);
3772                 let (announcement, bs_update) = match events_7[0] {
3773                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3774                                 (msg, update_msg)
3775                         },
3776                         _ => panic!("Unexpected event"),
3777                 };
3778
3779                 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs).unwrap();
3780                 let events_8 = node_a.node.get_and_clear_pending_msg_events();
3781                 assert_eq!(events_8.len(), 1);
3782                 let as_update = match events_8[0] {
3783                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3784                                 assert!(*announcement == *msg);
3785                                 update_msg
3786                         },
3787                         _ => panic!("Unexpected event"),
3788                 };
3789
3790                 *node_a.network_chan_count.borrow_mut() += 1;
3791
3792                 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
3793         }
3794
3795         fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3796                 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001)
3797         }
3798
3799         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) {
3800                 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat);
3801                 for node in nodes {
3802                         assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
3803                         node.router.handle_channel_update(&chan_announcement.1).unwrap();
3804                         node.router.handle_channel_update(&chan_announcement.2).unwrap();
3805                 }
3806                 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
3807         }
3808
3809         macro_rules! check_spends {
3810                 ($tx: expr, $spends_tx: expr) => {
3811                         {
3812                                 let mut funding_tx_map = HashMap::new();
3813                                 let spends_tx = $spends_tx;
3814                                 funding_tx_map.insert(spends_tx.txid(), spends_tx);
3815                                 $tx.verify(&funding_tx_map).unwrap();
3816                         }
3817                 }
3818         }
3819
3820         macro_rules! get_closing_signed_broadcast {
3821                 ($node: expr, $dest_pubkey: expr) => {
3822                         {
3823                                 let events = $node.get_and_clear_pending_msg_events();
3824                                 assert!(events.len() == 1 || events.len() == 2);
3825                                 (match events[events.len() - 1] {
3826                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
3827                                                 assert_eq!(msg.contents.flags & 2, 2);
3828                                                 msg.clone()
3829                                         },
3830                                         _ => panic!("Unexpected event"),
3831                                 }, if events.len() == 2 {
3832                                         match events[0] {
3833                                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3834                                                         assert_eq!(*node_id, $dest_pubkey);
3835                                                         Some(msg.clone())
3836                                                 },
3837                                                 _ => panic!("Unexpected event"),
3838                                         }
3839                                 } else { None })
3840                         }
3841                 }
3842         }
3843
3844         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) {
3845                 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) };
3846                 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
3847                 let (tx_a, tx_b);
3848
3849                 node_a.close_channel(channel_id).unwrap();
3850                 node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id())).unwrap();
3851
3852                 let events_1 = node_b.get_and_clear_pending_msg_events();
3853                 assert!(events_1.len() >= 1);
3854                 let shutdown_b = match events_1[0] {
3855                         MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
3856                                 assert_eq!(node_id, &node_a.get_our_node_id());
3857                                 msg.clone()
3858                         },
3859                         _ => panic!("Unexpected event"),
3860                 };
3861
3862                 let closing_signed_b = if !close_inbound_first {
3863                         assert_eq!(events_1.len(), 1);
3864                         None
3865                 } else {
3866                         Some(match events_1[1] {
3867                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3868                                         assert_eq!(node_id, &node_a.get_our_node_id());
3869                                         msg.clone()
3870                                 },
3871                                 _ => panic!("Unexpected event"),
3872                         })
3873                 };
3874
3875                 node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b).unwrap();
3876                 let (as_update, bs_update) = if close_inbound_first {
3877                         assert!(node_a.get_and_clear_pending_msg_events().is_empty());
3878                         node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3879                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3880                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3881                         let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3882
3883                         node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
3884                         let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3885                         assert!(none_b.is_none());
3886                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3887                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3888                         (as_update, bs_update)
3889                 } else {
3890                         let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
3891
3892                         node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a).unwrap();
3893                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3894                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3895                         let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3896
3897                         node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3898                         let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3899                         assert!(none_a.is_none());
3900                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3901                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3902                         (as_update, bs_update)
3903                 };
3904                 assert_eq!(tx_a, tx_b);
3905                 check_spends!(tx_a, funding_tx);
3906
3907                 (as_update, bs_update, tx_a)
3908         }
3909
3910         struct SendEvent {
3911                 node_id: PublicKey,
3912                 msgs: Vec<msgs::UpdateAddHTLC>,
3913                 commitment_msg: msgs::CommitmentSigned,
3914         }
3915         impl SendEvent {
3916                 fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
3917                         assert!(updates.update_fulfill_htlcs.is_empty());
3918                         assert!(updates.update_fail_htlcs.is_empty());
3919                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3920                         assert!(updates.update_fee.is_none());
3921                         SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
3922                 }
3923
3924                 fn from_event(event: MessageSendEvent) -> SendEvent {
3925                         match event {
3926                                 MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
3927                                 _ => panic!("Unexpected event type!"),
3928                         }
3929                 }
3930
3931                 fn from_node(node: &Node) -> SendEvent {
3932                         let mut events = node.node.get_and_clear_pending_msg_events();
3933                         assert_eq!(events.len(), 1);
3934                         SendEvent::from_event(events.pop().unwrap())
3935                 }
3936         }
3937
3938         macro_rules! check_added_monitors {
3939                 ($node: expr, $count: expr) => {
3940                         {
3941                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
3942                                 assert_eq!(added_monitors.len(), $count);
3943                                 added_monitors.clear();
3944                         }
3945                 }
3946         }
3947
3948         macro_rules! commitment_signed_dance {
3949                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
3950                         {
3951                                 check_added_monitors!($node_a, 0);
3952                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3953                                 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3954                                 check_added_monitors!($node_a, 1);
3955                                 commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
3956                         }
3957                 };
3958                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
3959                         {
3960                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
3961                                 check_added_monitors!($node_b, 0);
3962                                 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3963                                 $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
3964                                 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3965                                 check_added_monitors!($node_b, 1);
3966                                 $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed).unwrap();
3967                                 let (bs_revoke_and_ack, extra_msg_option) = {
3968                                         let events = $node_b.node.get_and_clear_pending_msg_events();
3969                                         assert!(events.len() <= 2);
3970                                         (match events[0] {
3971                                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3972                                                         assert_eq!(*node_id, $node_a.node.get_our_node_id());
3973                                                         (*msg).clone()
3974                                                 },
3975                                                 _ => panic!("Unexpected event"),
3976                                         }, events.get(1).map(|e| e.clone()))
3977                                 };
3978                                 check_added_monitors!($node_b, 1);
3979                                 if $fail_backwards {
3980                                         assert!($node_a.node.get_and_clear_pending_events().is_empty());
3981                                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3982                                 }
3983                                 (extra_msg_option, bs_revoke_and_ack)
3984                         }
3985                 };
3986                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
3987                         {
3988                                 check_added_monitors!($node_a, 0);
3989                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3990                                 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3991                                 check_added_monitors!($node_a, 1);
3992                                 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
3993                                 assert!(extra_msg_option.is_none());
3994                                 bs_revoke_and_ack
3995                         }
3996                 };
3997                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
3998                         {
3999                                 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
4000                                 $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
4001                                 {
4002                                         let mut added_monitors = $node_a.chan_monitor.added_monitors.lock().unwrap();
4003                                         if $fail_backwards {
4004                                                 assert_eq!(added_monitors.len(), 2);
4005                                                 assert!(added_monitors[0].0 != added_monitors[1].0);
4006                                         } else {
4007                                                 assert_eq!(added_monitors.len(), 1);
4008                                         }
4009                                         added_monitors.clear();
4010                                 }
4011                                 extra_msg_option
4012                         }
4013                 };
4014                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
4015                         {
4016                                 assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
4017                         }
4018                 };
4019                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
4020                         {
4021                                 commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
4022                                 if $fail_backwards {
4023                                         let channel_state = $node_a.node.channel_state.lock().unwrap();
4024                                         assert_eq!(channel_state.pending_msg_events.len(), 1);
4025                                         if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
4026                                                 assert_ne!(*node_id, $node_b.node.get_our_node_id());
4027                                         } else { panic!("Unexpected event"); }
4028                                 } else {
4029                                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
4030                                 }
4031                         }
4032                 }
4033         }
4034
4035         macro_rules! get_payment_preimage_hash {
4036                 ($node: expr) => {
4037                         {
4038                                 let payment_preimage = PaymentPreimage([*$node.network_payment_count.borrow(); 32]);
4039                                 *$node.network_payment_count.borrow_mut() += 1;
4040                                 let mut payment_hash = PaymentHash([0; 32]);
4041                                 let mut sha = Sha256::new();
4042                                 sha.input(&payment_preimage.0[..]);
4043                                 sha.result(&mut payment_hash.0[..]);
4044                                 (payment_preimage, payment_hash)
4045                         }
4046                 }
4047         }
4048
4049         fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
4050                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4051
4052                 let mut payment_event = {
4053                         origin_node.node.send_payment(route, our_payment_hash).unwrap();
4054                         check_added_monitors!(origin_node, 1);
4055
4056                         let mut events = origin_node.node.get_and_clear_pending_msg_events();
4057                         assert_eq!(events.len(), 1);
4058                         SendEvent::from_event(events.remove(0))
4059                 };
4060                 let mut prev_node = origin_node;
4061
4062                 for (idx, &node) in expected_route.iter().enumerate() {
4063                         assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
4064
4065                         node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4066                         check_added_monitors!(node, 0);
4067                         commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
4068
4069                         let events_1 = node.node.get_and_clear_pending_events();
4070                         assert_eq!(events_1.len(), 1);
4071                         match events_1[0] {
4072                                 Event::PendingHTLCsForwardable { .. } => { },
4073                                 _ => panic!("Unexpected event"),
4074                         };
4075
4076                         node.node.channel_state.lock().unwrap().next_forward = Instant::now();
4077                         node.node.process_pending_htlc_forwards();
4078
4079                         if idx == expected_route.len() - 1 {
4080                                 let events_2 = node.node.get_and_clear_pending_events();
4081                                 assert_eq!(events_2.len(), 1);
4082                                 match events_2[0] {
4083                                         Event::PaymentReceived { ref payment_hash, amt } => {
4084                                                 assert_eq!(our_payment_hash, *payment_hash);
4085                                                 assert_eq!(amt, recv_value);
4086                                         },
4087                                         _ => panic!("Unexpected event"),
4088                                 }
4089                         } else {
4090                                 let mut events_2 = node.node.get_and_clear_pending_msg_events();
4091                                 assert_eq!(events_2.len(), 1);
4092                                 check_added_monitors!(node, 1);
4093                                 payment_event = SendEvent::from_event(events_2.remove(0));
4094                                 assert_eq!(payment_event.msgs.len(), 1);
4095                         }
4096
4097                         prev_node = node;
4098                 }
4099
4100                 (our_payment_preimage, our_payment_hash)
4101         }
4102
4103         fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: PaymentPreimage) {
4104                 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
4105                 check_added_monitors!(expected_route.last().unwrap(), 1);
4106
4107                 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
4108                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4109                 macro_rules! get_next_msgs {
4110                         ($node: expr) => {
4111                                 {
4112                                         let events = $node.node.get_and_clear_pending_msg_events();
4113                                         assert_eq!(events.len(), 1);
4114                                         match events[0] {
4115                                                 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 } } => {
4116                                                         assert!(update_add_htlcs.is_empty());
4117                                                         assert_eq!(update_fulfill_htlcs.len(), 1);
4118                                                         assert!(update_fail_htlcs.is_empty());
4119                                                         assert!(update_fail_malformed_htlcs.is_empty());
4120                                                         assert!(update_fee.is_none());
4121                                                         expected_next_node = node_id.clone();
4122                                                         Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()))
4123                                                 },
4124                                                 _ => panic!("Unexpected event"),
4125                                         }
4126                                 }
4127                         }
4128                 }
4129
4130                 macro_rules! last_update_fulfill_dance {
4131                         ($node: expr, $prev_node: expr) => {
4132                                 {
4133                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4134                                         check_added_monitors!($node, 0);
4135                                         assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4136                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4137                                 }
4138                         }
4139                 }
4140                 macro_rules! mid_update_fulfill_dance {
4141                         ($node: expr, $prev_node: expr, $new_msgs: expr) => {
4142                                 {
4143                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4144                                         check_added_monitors!($node, 1);
4145                                         let new_next_msgs = if $new_msgs {
4146                                                 get_next_msgs!($node)
4147                                         } else {
4148                                                 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4149                                                 None
4150                                         };
4151                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4152                                         next_msgs = new_next_msgs;
4153                                 }
4154                         }
4155                 }
4156
4157                 let mut prev_node = expected_route.last().unwrap();
4158                 for (idx, node) in expected_route.iter().rev().enumerate() {
4159                         assert_eq!(expected_next_node, node.node.get_our_node_id());
4160                         let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
4161                         if next_msgs.is_some() {
4162                                 mid_update_fulfill_dance!(node, prev_node, update_next_msgs);
4163                         } else if update_next_msgs {
4164                                 next_msgs = get_next_msgs!(node);
4165                         } else {
4166                                 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
4167                         }
4168                         if !skip_last && idx == expected_route.len() - 1 {
4169                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4170                         }
4171
4172                         prev_node = node;
4173                 }
4174
4175                 if !skip_last {
4176                         last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
4177                         let events = origin_node.node.get_and_clear_pending_events();
4178                         assert_eq!(events.len(), 1);
4179                         match events[0] {
4180                                 Event::PaymentSent { payment_preimage } => {
4181                                         assert_eq!(payment_preimage, our_payment_preimage);
4182                                 },
4183                                 _ => panic!("Unexpected event"),
4184                         }
4185                 }
4186         }
4187
4188         fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: PaymentPreimage) {
4189                 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage);
4190         }
4191
4192         const TEST_FINAL_CLTV: u32 = 32;
4193
4194         fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
4195                 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();
4196                 assert_eq!(route.hops.len(), expected_route.len());
4197                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4198                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
4199                 }
4200
4201                 send_along_route(origin_node, route, expected_route, recv_value)
4202         }
4203
4204         fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
4205                 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();
4206                 assert_eq!(route.hops.len(), expected_route.len());
4207                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4208                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
4209                 }
4210
4211                 let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4212
4213                 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
4214                 match err {
4215                         APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
4216                         _ => panic!("Unknown error variants"),
4217                 };
4218         }
4219
4220         fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
4221                 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
4222                 claim_payment(&origin, expected_route, our_payment_preimage);
4223         }
4224
4225         fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: PaymentHash) {
4226                 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash, PaymentFailReason::PreimageUnknown));
4227                 check_added_monitors!(expected_route.last().unwrap(), 1);
4228
4229                 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
4230                 macro_rules! update_fail_dance {
4231                         ($node: expr, $prev_node: expr, $last_node: expr) => {
4232                                 {
4233                                         $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4234                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
4235                                 }
4236                         }
4237                 }
4238
4239                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4240                 let mut prev_node = expected_route.last().unwrap();
4241                 for (idx, node) in expected_route.iter().rev().enumerate() {
4242                         assert_eq!(expected_next_node, node.node.get_our_node_id());
4243                         if next_msgs.is_some() {
4244                                 // We may be the "last node" for the purpose of the commitment dance if we're
4245                                 // skipping the last node (implying it is disconnected) and we're the
4246                                 // second-to-last node!
4247                                 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
4248                         }
4249
4250                         let events = node.node.get_and_clear_pending_msg_events();
4251                         if !skip_last || idx != expected_route.len() - 1 {
4252                                 assert_eq!(events.len(), 1);
4253                                 match events[0] {
4254                                         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 } } => {
4255                                                 assert!(update_add_htlcs.is_empty());
4256                                                 assert!(update_fulfill_htlcs.is_empty());
4257                                                 assert_eq!(update_fail_htlcs.len(), 1);
4258                                                 assert!(update_fail_malformed_htlcs.is_empty());
4259                                                 assert!(update_fee.is_none());
4260                                                 expected_next_node = node_id.clone();
4261                                                 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
4262                                         },
4263                                         _ => panic!("Unexpected event"),
4264                                 }
4265                         } else {
4266                                 assert!(events.is_empty());
4267                         }
4268                         if !skip_last && idx == expected_route.len() - 1 {
4269                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4270                         }
4271
4272                         prev_node = node;
4273                 }
4274
4275                 if !skip_last {
4276                         update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
4277
4278                         let events = origin_node.node.get_and_clear_pending_events();
4279                         assert_eq!(events.len(), 1);
4280                         match events[0] {
4281                                 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
4282                                         assert_eq!(payment_hash, our_payment_hash);
4283                                         assert!(rejected_by_dest);
4284                                 },
4285                                 _ => panic!("Unexpected event"),
4286                         }
4287                 }
4288         }
4289
4290         fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: PaymentHash) {
4291                 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
4292         }
4293
4294         fn create_network(node_count: usize) -> Vec<Node> {
4295                 let mut nodes = Vec::new();
4296                 let mut rng = thread_rng();
4297                 let secp_ctx = Secp256k1::new();
4298
4299                 let chan_count = Rc::new(RefCell::new(0));
4300                 let payment_count = Rc::new(RefCell::new(0));
4301
4302                 for i in 0..node_count {
4303                         let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
4304                         let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
4305                         let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
4306                         let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
4307                         let mut seed = [0; 32];
4308                         rng.fill_bytes(&mut seed);
4309                         let keys_manager = Arc::new(keysinterface::KeysManager::new(&seed, Network::Testnet, Arc::clone(&logger)));
4310                         let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone()));
4311                         let mut config = UserConfig::new();
4312                         config.channel_options.announced_channel = true;
4313                         config.channel_limits.force_announced_channel_preference = false;
4314                         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();
4315                         let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), chain_monitor.clone(), Arc::clone(&logger));
4316                         nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router, node_seed: seed,
4317                                 network_payment_count: payment_count.clone(),
4318                                 network_chan_count: chan_count.clone(),
4319                         });
4320                 }
4321
4322                 nodes
4323         }
4324
4325         #[test]
4326         fn test_async_inbound_update_fee() {
4327                 let mut nodes = create_network(2);
4328                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4329                 let channel_id = chan.2;
4330
4331                 // balancing
4332                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4333
4334                 // A                                        B
4335                 // update_fee                            ->
4336                 // send (1) commitment_signed            -.
4337                 //                                       <- update_add_htlc/commitment_signed
4338                 // send (2) RAA (awaiting remote revoke) -.
4339                 // (1) commitment_signed is delivered    ->
4340                 //                                       .- send (3) RAA (awaiting remote revoke)
4341                 // (2) RAA is delivered                  ->
4342                 //                                       .- send (4) commitment_signed
4343                 //                                       <- (3) RAA is delivered
4344                 // send (5) commitment_signed            -.
4345                 //                                       <- (4) commitment_signed is delivered
4346                 // send (6) RAA                          -.
4347                 // (5) commitment_signed is delivered    ->
4348                 //                                       <- RAA
4349                 // (6) RAA is delivered                  ->
4350
4351                 // First nodes[0] generates an update_fee
4352                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4353                 check_added_monitors!(nodes[0], 1);
4354
4355                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4356                 assert_eq!(events_0.len(), 1);
4357                 let (update_msg, commitment_signed) = match events_0[0] { // (1)
4358                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4359                                 (update_fee.as_ref(), commitment_signed)
4360                         },
4361                         _ => panic!("Unexpected event"),
4362                 };
4363
4364                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4365
4366                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4367                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4368                 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();
4369                 check_added_monitors!(nodes[1], 1);
4370
4371                 let payment_event = {
4372                         let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4373                         assert_eq!(events_1.len(), 1);
4374                         SendEvent::from_event(events_1.remove(0))
4375                 };
4376                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4377                 assert_eq!(payment_event.msgs.len(), 1);
4378
4379                 // ...now when the messages get delivered everyone should be happy
4380                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4381                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4382                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4383                 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4384                 check_added_monitors!(nodes[0], 1);
4385
4386                 // deliver(1), generate (3):
4387                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4388                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4389                 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
4390                 check_added_monitors!(nodes[1], 1);
4391
4392                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap(); // deliver (2)
4393                 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4394                 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
4395                 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
4396                 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
4397                 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
4398                 assert!(bs_update.update_fee.is_none()); // (4)
4399                 check_added_monitors!(nodes[1], 1);
4400
4401                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap(); // deliver (3)
4402                 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4403                 assert!(as_update.update_add_htlcs.is_empty()); // (5)
4404                 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
4405                 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
4406                 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
4407                 assert!(as_update.update_fee.is_none()); // (5)
4408                 check_added_monitors!(nodes[0], 1);
4409
4410                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed).unwrap(); // deliver (4)
4411                 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4412                 // only (6) so get_event_msg's assert(len == 1) passes
4413                 check_added_monitors!(nodes[0], 1);
4414
4415                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed).unwrap(); // deliver (5)
4416                 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4417                 check_added_monitors!(nodes[1], 1);
4418
4419                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4420                 check_added_monitors!(nodes[0], 1);
4421
4422                 let events_2 = nodes[0].node.get_and_clear_pending_events();
4423                 assert_eq!(events_2.len(), 1);
4424                 match events_2[0] {
4425                         Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
4426                         _ => panic!("Unexpected event"),
4427                 }
4428
4429                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap(); // deliver (6)
4430                 check_added_monitors!(nodes[1], 1);
4431         }
4432
4433         #[test]
4434         fn test_update_fee_unordered_raa() {
4435                 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
4436                 // crash in an earlier version of the update_fee patch)
4437                 let mut nodes = create_network(2);
4438                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4439                 let channel_id = chan.2;
4440
4441                 // balancing
4442                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4443
4444                 // First nodes[0] generates an update_fee
4445                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4446                 check_added_monitors!(nodes[0], 1);
4447
4448                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4449                 assert_eq!(events_0.len(), 1);
4450                 let update_msg = match events_0[0] { // (1)
4451                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
4452                                 update_fee.as_ref()
4453                         },
4454                         _ => panic!("Unexpected event"),
4455                 };
4456
4457                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4458
4459                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4460                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4461                 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();
4462                 check_added_monitors!(nodes[1], 1);
4463
4464                 let payment_event = {
4465                         let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4466                         assert_eq!(events_1.len(), 1);
4467                         SendEvent::from_event(events_1.remove(0))
4468                 };
4469                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4470                 assert_eq!(payment_event.msgs.len(), 1);
4471
4472                 // ...now when the messages get delivered everyone should be happy
4473                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4474                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4475                 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4476                 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4477                 check_added_monitors!(nodes[0], 1);
4478
4479                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap(); // deliver (2)
4480                 check_added_monitors!(nodes[1], 1);
4481
4482                 // We can't continue, sadly, because our (1) now has a bogus signature
4483         }
4484
4485         #[test]
4486         fn test_multi_flight_update_fee() {
4487                 let nodes = create_network(2);
4488                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4489                 let channel_id = chan.2;
4490
4491                 // A                                        B
4492                 // update_fee/commitment_signed          ->
4493                 //                                       .- send (1) RAA and (2) commitment_signed
4494                 // update_fee (never committed)          ->
4495                 // (3) update_fee                        ->
4496                 // We have to manually generate the above update_fee, it is allowed by the protocol but we
4497                 // don't track which updates correspond to which revoke_and_ack responses so we're in
4498                 // AwaitingRAA mode and will not generate the update_fee yet.
4499                 //                                       <- (1) RAA delivered
4500                 // (3) is generated and send (4) CS      -.
4501                 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
4502                 // know the per_commitment_point to use for it.
4503                 //                                       <- (2) commitment_signed delivered
4504                 // revoke_and_ack                        ->
4505                 //                                          B should send no response here
4506                 // (4) commitment_signed delivered       ->
4507                 //                                       <- RAA/commitment_signed delivered
4508                 // revoke_and_ack                        ->
4509
4510                 // First nodes[0] generates an update_fee
4511                 let initial_feerate = get_feerate!(nodes[0], channel_id);
4512                 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
4513                 check_added_monitors!(nodes[0], 1);
4514
4515                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4516                 assert_eq!(events_0.len(), 1);
4517                 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
4518                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4519                                 (update_fee.as_ref().unwrap(), commitment_signed)
4520                         },
4521                         _ => panic!("Unexpected event"),
4522                 };
4523
4524                 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
4525                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1).unwrap();
4526                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1).unwrap();
4527                 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4528                 check_added_monitors!(nodes[1], 1);
4529
4530                 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
4531                 // transaction:
4532                 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
4533                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4534                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4535
4536                 // Create the (3) update_fee message that nodes[0] will generate before it does...
4537                 let mut update_msg_2 = msgs::UpdateFee {
4538                         channel_id: update_msg_1.channel_id.clone(),
4539                         feerate_per_kw: (initial_feerate + 30) as u32,
4540                 };
4541
4542                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4543
4544                 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
4545                 // Deliver (3)
4546                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4547
4548                 // Deliver (1), generating (3) and (4)
4549                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap();
4550                 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4551                 check_added_monitors!(nodes[0], 1);
4552                 assert!(as_second_update.update_add_htlcs.is_empty());
4553                 assert!(as_second_update.update_fulfill_htlcs.is_empty());
4554                 assert!(as_second_update.update_fail_htlcs.is_empty());
4555                 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
4556                 // Check that the update_fee newly generated matches what we delivered:
4557                 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
4558                 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
4559
4560                 // Deliver (2) commitment_signed
4561                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
4562                 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4563                 check_added_monitors!(nodes[0], 1);
4564                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4565
4566                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap();
4567                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4568                 check_added_monitors!(nodes[1], 1);
4569
4570                 // Delever (4)
4571                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed).unwrap();
4572                 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4573                 check_added_monitors!(nodes[1], 1);
4574
4575                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4576                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4577                 check_added_monitors!(nodes[0], 1);
4578
4579                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment).unwrap();
4580                 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4581                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4582                 check_added_monitors!(nodes[0], 1);
4583
4584                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap();
4585                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4586                 check_added_monitors!(nodes[1], 1);
4587         }
4588
4589         #[test]
4590         fn test_update_fee_vanilla() {
4591                 let nodes = create_network(2);
4592                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4593                 let channel_id = chan.2;
4594
4595                 let feerate = get_feerate!(nodes[0], channel_id);
4596                 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
4597                 check_added_monitors!(nodes[0], 1);
4598
4599                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4600                 assert_eq!(events_0.len(), 1);
4601                 let (update_msg, commitment_signed) = match events_0[0] {
4602                                 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 } } => {
4603                                 (update_fee.as_ref(), commitment_signed)
4604                         },
4605                         _ => panic!("Unexpected event"),
4606                 };
4607                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4608
4609                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4610                 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4611                 check_added_monitors!(nodes[1], 1);
4612
4613                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4614                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4615                 check_added_monitors!(nodes[0], 1);
4616
4617                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4618                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4619                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4620                 check_added_monitors!(nodes[0], 1);
4621
4622                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4623                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4624                 check_added_monitors!(nodes[1], 1);
4625         }
4626
4627         #[test]
4628         fn test_update_fee_that_funder_cannot_afford() {
4629                 let nodes = create_network(2);
4630                 let channel_value = 1888;
4631                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000);
4632                 let channel_id = chan.2;
4633
4634                 let feerate = 260;
4635                 nodes[0].node.update_fee(channel_id, feerate).unwrap();
4636                 check_added_monitors!(nodes[0], 1);
4637                 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4638
4639                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap()).unwrap();
4640
4641                 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
4642
4643                 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
4644                 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
4645                 {
4646                         let chan_lock = nodes[1].node.channel_state.lock().unwrap();
4647                         let chan = chan_lock.by_id.get(&channel_id).unwrap();
4648
4649                         //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
4650                         let num_htlcs = chan.last_local_commitment_txn[0].output.len() - 2;
4651                         let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
4652                         let mut actual_fee = chan.last_local_commitment_txn[0].output.iter().fold(0, |acc, output| acc + output.value);
4653                         actual_fee = channel_value - actual_fee;
4654                         assert_eq!(total_fee, actual_fee);
4655                 } //drop the mutex
4656
4657                 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
4658                 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
4659                 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
4660                 check_added_monitors!(nodes[0], 1);
4661
4662                 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4663
4664                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap()).unwrap();
4665
4666                 //While producing the commitment_signed response after handling a received update_fee request the
4667                 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
4668                 //Should produce and error.
4669                 let err = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed).unwrap_err();
4670
4671                 assert!(match err.err {
4672                         "Funding remote cannot afford proposed new fee" => true,
4673                         _ => false,
4674                 });
4675
4676                 //clear the message we could not handle
4677                 nodes[1].node.get_and_clear_pending_msg_events();
4678         }
4679
4680         #[test]
4681         fn test_update_fee_with_fundee_update_add_htlc() {
4682                 let mut nodes = create_network(2);
4683                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4684                 let channel_id = chan.2;
4685
4686                 // balancing
4687                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4688
4689                 let feerate = get_feerate!(nodes[0], channel_id);
4690                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4691                 check_added_monitors!(nodes[0], 1);
4692
4693                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4694                 assert_eq!(events_0.len(), 1);
4695                 let (update_msg, commitment_signed) = match events_0[0] {
4696                                 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 } } => {
4697                                 (update_fee.as_ref(), commitment_signed)
4698                         },
4699                         _ => panic!("Unexpected event"),
4700                 };
4701                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4702                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4703                 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4704                 check_added_monitors!(nodes[1], 1);
4705
4706                 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
4707
4708                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
4709
4710                 // nothing happens since node[1] is in AwaitingRemoteRevoke
4711                 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
4712                 {
4713                         let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
4714                         assert_eq!(added_monitors.len(), 0);
4715                         added_monitors.clear();
4716                 }
4717                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4718                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4719                 // node[1] has nothing to do
4720
4721                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4722                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4723                 check_added_monitors!(nodes[0], 1);
4724
4725                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4726                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4727                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4728                 check_added_monitors!(nodes[0], 1);
4729                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4730                 check_added_monitors!(nodes[1], 1);
4731                 // AwaitingRemoteRevoke ends here
4732
4733                 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4734                 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
4735                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
4736                 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
4737                 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
4738                 assert_eq!(commitment_update.update_fee.is_none(), true);
4739
4740                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]).unwrap();
4741                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4742                 check_added_monitors!(nodes[0], 1);
4743                 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4744
4745                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke).unwrap();
4746                 check_added_monitors!(nodes[1], 1);
4747                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4748
4749                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed).unwrap();
4750                 check_added_monitors!(nodes[1], 1);
4751                 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4752                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4753
4754                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke).unwrap();
4755                 check_added_monitors!(nodes[0], 1);
4756                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4757
4758                 let events = nodes[0].node.get_and_clear_pending_events();
4759                 assert_eq!(events.len(), 1);
4760                 match events[0] {
4761                         Event::PendingHTLCsForwardable { .. } => { },
4762                         _ => panic!("Unexpected event"),
4763                 };
4764                 nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
4765                 nodes[0].node.process_pending_htlc_forwards();
4766
4767                 let events = nodes[0].node.get_and_clear_pending_events();
4768                 assert_eq!(events.len(), 1);
4769                 match events[0] {
4770                         Event::PaymentReceived { .. } => { },
4771                         _ => panic!("Unexpected event"),
4772                 };
4773
4774                 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
4775
4776                 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
4777                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
4778                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4779         }
4780
4781         #[test]
4782         fn test_update_fee() {
4783                 let nodes = create_network(2);
4784                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4785                 let channel_id = chan.2;
4786
4787                 // A                                        B
4788                 // (1) update_fee/commitment_signed      ->
4789                 //                                       <- (2) revoke_and_ack
4790                 //                                       .- send (3) commitment_signed
4791                 // (4) update_fee/commitment_signed      ->
4792                 //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
4793                 //                                       <- (3) commitment_signed delivered
4794                 // send (6) revoke_and_ack               -.
4795                 //                                       <- (5) deliver revoke_and_ack
4796                 // (6) deliver revoke_and_ack            ->
4797                 //                                       .- send (7) commitment_signed in response to (4)
4798                 //                                       <- (7) deliver commitment_signed
4799                 // revoke_and_ack                        ->
4800
4801                 // Create and deliver (1)...
4802                 let feerate = get_feerate!(nodes[0], channel_id);
4803                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4804                 check_added_monitors!(nodes[0], 1);
4805
4806                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4807                 assert_eq!(events_0.len(), 1);
4808                 let (update_msg, commitment_signed) = match events_0[0] {
4809                                 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 } } => {
4810                                 (update_fee.as_ref(), commitment_signed)
4811                         },
4812                         _ => panic!("Unexpected event"),
4813                 };
4814                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4815
4816                 // Generate (2) and (3):
4817                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4818                 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4819                 check_added_monitors!(nodes[1], 1);
4820
4821                 // Deliver (2):
4822                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4823                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4824                 check_added_monitors!(nodes[0], 1);
4825
4826                 // Create and deliver (4)...
4827                 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
4828                 check_added_monitors!(nodes[0], 1);
4829                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4830                 assert_eq!(events_0.len(), 1);
4831                 let (update_msg, commitment_signed) = match events_0[0] {
4832                                 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 } } => {
4833                                 (update_fee.as_ref(), commitment_signed)
4834                         },
4835                         _ => panic!("Unexpected event"),
4836                 };
4837
4838                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4839                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4840                 check_added_monitors!(nodes[1], 1);
4841                 // ... creating (5)
4842                 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4843                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4844
4845                 // Handle (3), creating (6):
4846                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0).unwrap();
4847                 check_added_monitors!(nodes[0], 1);
4848                 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4849                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4850
4851                 // Deliver (5):
4852                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4853                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4854                 check_added_monitors!(nodes[0], 1);
4855
4856                 // Deliver (6), creating (7):
4857                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0).unwrap();
4858                 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4859                 assert!(commitment_update.update_add_htlcs.is_empty());
4860                 assert!(commitment_update.update_fulfill_htlcs.is_empty());
4861                 assert!(commitment_update.update_fail_htlcs.is_empty());
4862                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
4863                 assert!(commitment_update.update_fee.is_none());
4864                 check_added_monitors!(nodes[1], 1);
4865
4866                 // Deliver (7)
4867                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4868                 check_added_monitors!(nodes[0], 1);
4869                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4870                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4871
4872                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4873                 check_added_monitors!(nodes[1], 1);
4874                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4875
4876                 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
4877                 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
4878                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4879         }
4880
4881         #[test]
4882         fn pre_funding_lock_shutdown_test() {
4883                 // Test sending a shutdown prior to funding_locked after funding generation
4884                 let nodes = create_network(2);
4885                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0);
4886                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4887                 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4888                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4889
4890                 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
4891                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4892                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4893                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4894                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4895
4896                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4897                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4898                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4899                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4900                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4901                 assert!(node_0_none.is_none());
4902
4903                 assert!(nodes[0].node.list_channels().is_empty());
4904                 assert!(nodes[1].node.list_channels().is_empty());
4905         }
4906
4907         #[test]
4908         fn updates_shutdown_wait() {
4909                 // Test sending a shutdown with outstanding updates pending
4910                 let mut nodes = create_network(3);
4911                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4912                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4913                 let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4914                 let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4915
4916                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
4917
4918                 nodes[0].node.close_channel(&chan_1.2).unwrap();
4919                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4920                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4921                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4922                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4923
4924                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4925                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4926
4927                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4928                 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route_1, payment_hash) {}
4929                 else { panic!("New sends should fail!") };
4930                 if let Err(APIError::ChannelUnavailable {..}) = nodes[1].node.send_payment(route_2, payment_hash) {}
4931                 else { panic!("New sends should fail!") };
4932
4933                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
4934                 check_added_monitors!(nodes[2], 1);
4935                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4936                 assert!(updates.update_add_htlcs.is_empty());
4937                 assert!(updates.update_fail_htlcs.is_empty());
4938                 assert!(updates.update_fail_malformed_htlcs.is_empty());
4939                 assert!(updates.update_fee.is_none());
4940                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4941                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
4942                 check_added_monitors!(nodes[1], 1);
4943                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4944                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
4945
4946                 assert!(updates_2.update_add_htlcs.is_empty());
4947                 assert!(updates_2.update_fail_htlcs.is_empty());
4948                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
4949                 assert!(updates_2.update_fee.is_none());
4950                 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
4951                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
4952                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
4953
4954                 let events = nodes[0].node.get_and_clear_pending_events();
4955                 assert_eq!(events.len(), 1);
4956                 match events[0] {
4957                         Event::PaymentSent { ref payment_preimage } => {
4958                                 assert_eq!(our_payment_preimage, *payment_preimage);
4959                         },
4960                         _ => panic!("Unexpected event"),
4961                 }
4962
4963                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4964                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4965                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4966                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4967                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4968                 assert!(node_0_none.is_none());
4969
4970                 assert!(nodes[0].node.list_channels().is_empty());
4971
4972                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4973                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
4974                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
4975                 assert!(nodes[1].node.list_channels().is_empty());
4976                 assert!(nodes[2].node.list_channels().is_empty());
4977         }
4978
4979         #[test]
4980         fn htlc_fail_async_shutdown() {
4981                 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
4982                 let mut nodes = create_network(3);
4983                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4984                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4985
4986                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4987                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4988                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
4989                 check_added_monitors!(nodes[0], 1);
4990                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4991                 assert_eq!(updates.update_add_htlcs.len(), 1);
4992                 assert!(updates.update_fulfill_htlcs.is_empty());
4993                 assert!(updates.update_fail_htlcs.is_empty());
4994                 assert!(updates.update_fail_malformed_htlcs.is_empty());
4995                 assert!(updates.update_fee.is_none());
4996
4997                 nodes[1].node.close_channel(&chan_1.2).unwrap();
4998                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4999                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
5000                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5001
5002                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5003                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
5004                 check_added_monitors!(nodes[1], 1);
5005                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
5006                 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
5007
5008                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5009                 assert!(updates_2.update_add_htlcs.is_empty());
5010                 assert!(updates_2.update_fulfill_htlcs.is_empty());
5011                 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
5012                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
5013                 assert!(updates_2.update_fee.is_none());
5014
5015                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]).unwrap();
5016                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
5017
5018                 let events = nodes[0].node.get_and_clear_pending_events();
5019                 assert_eq!(events.len(), 1);
5020                 match events[0] {
5021                         Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } => {
5022                                 assert_eq!(our_payment_hash, *payment_hash);
5023                                 assert!(!rejected_by_dest);
5024                         },
5025                         _ => panic!("Unexpected event"),
5026                 }
5027
5028                 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5029                 assert_eq!(msg_events.len(), 2);
5030                 let node_0_closing_signed = match msg_events[0] {
5031                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
5032                                 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5033                                 (*msg).clone()
5034                         },
5035                         _ => panic!("Unexpected event"),
5036                 };
5037                 match msg_events[1] {
5038                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
5039                                 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
5040                         },
5041                         _ => panic!("Unexpected event"),
5042                 }
5043
5044                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5045                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5046                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5047                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5048                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5049                 assert!(node_0_none.is_none());
5050
5051                 assert!(nodes[0].node.list_channels().is_empty());
5052
5053                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5054                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5055                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5056                 assert!(nodes[1].node.list_channels().is_empty());
5057                 assert!(nodes[2].node.list_channels().is_empty());
5058         }
5059
5060         fn do_test_shutdown_rebroadcast(recv_count: u8) {
5061                 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
5062                 // messages delivered prior to disconnect
5063                 let nodes = create_network(3);
5064                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5065                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5066
5067                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
5068
5069                 nodes[1].node.close_channel(&chan_1.2).unwrap();
5070                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5071                 if recv_count > 0 {
5072                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
5073                         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5074                         if recv_count > 1 {
5075                                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
5076                         }
5077                 }
5078
5079                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5080                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5081
5082                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5083                 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5084                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5085                 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5086
5087                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish).unwrap();
5088                 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5089                 assert!(node_1_shutdown == node_1_2nd_shutdown);
5090
5091                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish).unwrap();
5092                 let node_0_2nd_shutdown = if recv_count > 0 {
5093                         let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5094                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5095                         node_0_2nd_shutdown
5096                 } else {
5097                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5098                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5099                         get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
5100                 };
5101                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown).unwrap();
5102
5103                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5104                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5105
5106                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
5107                 check_added_monitors!(nodes[2], 1);
5108                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5109                 assert!(updates.update_add_htlcs.is_empty());
5110                 assert!(updates.update_fail_htlcs.is_empty());
5111                 assert!(updates.update_fail_malformed_htlcs.is_empty());
5112                 assert!(updates.update_fee.is_none());
5113                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5114                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
5115                 check_added_monitors!(nodes[1], 1);
5116                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5117                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
5118
5119                 assert!(updates_2.update_add_htlcs.is_empty());
5120                 assert!(updates_2.update_fail_htlcs.is_empty());
5121                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
5122                 assert!(updates_2.update_fee.is_none());
5123                 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
5124                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
5125                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
5126
5127                 let events = nodes[0].node.get_and_clear_pending_events();
5128                 assert_eq!(events.len(), 1);
5129                 match events[0] {
5130                         Event::PaymentSent { ref payment_preimage } => {
5131                                 assert_eq!(our_payment_preimage, *payment_preimage);
5132                         },
5133                         _ => panic!("Unexpected event"),
5134                 }
5135
5136                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5137                 if recv_count > 0 {
5138                         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5139                         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5140                         assert!(node_1_closing_signed.is_some());
5141                 }
5142
5143                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5144                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5145
5146                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5147                 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5148                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5149                 if recv_count == 0 {
5150                         // If all closing_signeds weren't delivered we can just resume where we left off...
5151                         let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5152
5153                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish).unwrap();
5154                         let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5155                         assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
5156
5157                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish).unwrap();
5158                         let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5159                         assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
5160
5161                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown).unwrap();
5162                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5163
5164                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown).unwrap();
5165                         let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5166                         assert!(node_0_closing_signed == node_0_2nd_closing_signed);
5167
5168                         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed).unwrap();
5169                         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5170                         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5171                         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5172                         assert!(node_0_none.is_none());
5173                 } else {
5174                         // If one node, however, received + responded with an identical closing_signed we end
5175                         // up erroring and node[0] will try to broadcast its own latest commitment transaction.
5176                         // There isn't really anything better we can do simply, but in the future we might
5177                         // explore storing a set of recently-closed channels that got disconnected during
5178                         // closing_signed and avoiding broadcasting local commitment txn for some timeout to
5179                         // give our counterparty enough time to (potentially) broadcast a cooperative closing
5180                         // transaction.
5181                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5182
5183                         if let Err(msgs::HandleError{action: Some(msgs::ErrorAction::SendErrorMessage{msg}), ..}) =
5184                                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish) {
5185                                 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
5186                                 let msgs::ErrorMessage {ref channel_id, ..} = msg;
5187                                 assert_eq!(*channel_id, chan_1.2);
5188                         } else { panic!("Needed SendErrorMessage close"); }
5189
5190                         // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
5191                         // checks it, but in this case nodes[0] didn't ever get a chance to receive a
5192                         // closing_signed so we do it ourselves
5193                         let events = nodes[0].node.get_and_clear_pending_msg_events();
5194                         assert_eq!(events.len(), 1);
5195                         match events[0] {
5196                                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5197                                         assert_eq!(msg.contents.flags & 2, 2);
5198                                 },
5199                                 _ => panic!("Unexpected event"),
5200                         }
5201                 }
5202
5203                 assert!(nodes[0].node.list_channels().is_empty());
5204
5205                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5206                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5207                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5208                 assert!(nodes[1].node.list_channels().is_empty());
5209                 assert!(nodes[2].node.list_channels().is_empty());
5210         }
5211
5212         #[test]
5213         fn test_shutdown_rebroadcast() {
5214                 do_test_shutdown_rebroadcast(0);
5215                 do_test_shutdown_rebroadcast(1);
5216                 do_test_shutdown_rebroadcast(2);
5217         }
5218
5219         #[test]
5220         fn fake_network_test() {
5221                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5222                 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
5223                 let nodes = create_network(4);
5224
5225                 // Create some initial channels
5226                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5227                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5228                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5229
5230                 // Rebalance the network a bit by relaying one payment through all the channels...
5231                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5232                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5233                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5234                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5235
5236                 // Send some more payments
5237                 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
5238                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
5239                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
5240
5241                 // Test failure packets
5242                 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
5243                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
5244
5245                 // Add a new channel that skips 3
5246                 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
5247
5248                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
5249                 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
5250                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5251                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5252                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5253                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5254                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5255
5256                 // Do some rebalance loop payments, simultaneously
5257                 let mut hops = Vec::with_capacity(3);
5258                 hops.push(RouteHop {
5259                         pubkey: nodes[2].node.get_our_node_id(),
5260                         short_channel_id: chan_2.0.contents.short_channel_id,
5261                         fee_msat: 0,
5262                         cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
5263                 });
5264                 hops.push(RouteHop {
5265                         pubkey: nodes[3].node.get_our_node_id(),
5266                         short_channel_id: chan_3.0.contents.short_channel_id,
5267                         fee_msat: 0,
5268                         cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
5269                 });
5270                 hops.push(RouteHop {
5271                         pubkey: nodes[1].node.get_our_node_id(),
5272                         short_channel_id: chan_4.0.contents.short_channel_id,
5273                         fee_msat: 1000000,
5274                         cltv_expiry_delta: TEST_FINAL_CLTV,
5275                 });
5276                 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;
5277                 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;
5278                 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
5279
5280                 let mut hops = Vec::with_capacity(3);
5281                 hops.push(RouteHop {
5282                         pubkey: nodes[3].node.get_our_node_id(),
5283                         short_channel_id: chan_4.0.contents.short_channel_id,
5284                         fee_msat: 0,
5285                         cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
5286                 });
5287                 hops.push(RouteHop {
5288                         pubkey: nodes[2].node.get_our_node_id(),
5289                         short_channel_id: chan_3.0.contents.short_channel_id,
5290                         fee_msat: 0,
5291                         cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
5292                 });
5293                 hops.push(RouteHop {
5294                         pubkey: nodes[1].node.get_our_node_id(),
5295                         short_channel_id: chan_2.0.contents.short_channel_id,
5296                         fee_msat: 1000000,
5297                         cltv_expiry_delta: TEST_FINAL_CLTV,
5298                 });
5299                 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;
5300                 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;
5301                 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
5302
5303                 // Claim the rebalances...
5304                 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
5305                 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
5306
5307                 // Add a duplicate new channel from 2 to 4
5308                 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3);
5309
5310                 // Send some payments across both channels
5311                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5312                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5313                 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5314
5315                 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
5316
5317                 //TODO: Test that routes work again here as we've been notified that the channel is full
5318
5319                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
5320                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
5321                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
5322
5323                 // Close down the channels...
5324                 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
5325                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
5326                 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
5327                 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
5328                 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
5329         }
5330
5331         #[test]
5332         fn duplicate_htlc_test() {
5333                 // Test that we accept duplicate payment_hash HTLCs across the network and that
5334                 // claiming/failing them are all separate and don't effect each other
5335                 let mut nodes = create_network(6);
5336
5337                 // Create some initial channels to route via 3 to 4/5 from 0/1/2
5338                 create_announced_chan_between_nodes(&nodes, 0, 3);
5339                 create_announced_chan_between_nodes(&nodes, 1, 3);
5340                 create_announced_chan_between_nodes(&nodes, 2, 3);
5341                 create_announced_chan_between_nodes(&nodes, 3, 4);
5342                 create_announced_chan_between_nodes(&nodes, 3, 5);
5343
5344                 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
5345
5346                 *nodes[0].network_payment_count.borrow_mut() -= 1;
5347                 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
5348
5349                 *nodes[0].network_payment_count.borrow_mut() -= 1;
5350                 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
5351
5352                 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
5353                 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
5354                 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
5355         }
5356
5357         #[derive(PartialEq)]
5358         enum HTLCType { NONE, TIMEOUT, SUCCESS }
5359         /// Tests that the given node has broadcast transactions for the given Channel
5360         ///
5361         /// First checks that the latest local commitment tx has been broadcast, unless an explicit
5362         /// commitment_tx is provided, which may be used to test that a remote commitment tx was
5363         /// broadcast and the revoked outputs were claimed.
5364         ///
5365         /// Next tests that there is (or is not) a transaction that spends the commitment transaction
5366         /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
5367         ///
5368         /// All broadcast transactions must be accounted for in one of the above three types of we'll
5369         /// also fail.
5370         fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
5371                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5372                 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
5373
5374                 let mut res = Vec::with_capacity(2);
5375                 node_txn.retain(|tx| {
5376                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
5377                                 check_spends!(tx, chan.3.clone());
5378                                 if commitment_tx.is_none() {
5379                                         res.push(tx.clone());
5380                                 }
5381                                 false
5382                         } else { true }
5383                 });
5384                 if let Some(explicit_tx) = commitment_tx {
5385                         res.push(explicit_tx.clone());
5386                 }
5387
5388                 assert_eq!(res.len(), 1);
5389
5390                 if has_htlc_tx != HTLCType::NONE {
5391                         node_txn.retain(|tx| {
5392                                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
5393                                         check_spends!(tx, res[0].clone());
5394                                         if has_htlc_tx == HTLCType::TIMEOUT {
5395                                                 assert!(tx.lock_time != 0);
5396                                         } else {
5397                                                 assert!(tx.lock_time == 0);
5398                                         }
5399                                         res.push(tx.clone());
5400                                         false
5401                                 } else { true }
5402                         });
5403                         assert!(res.len() == 2 || res.len() == 3);
5404                         if res.len() == 3 {
5405                                 assert_eq!(res[1], res[2]);
5406                         }
5407                 }
5408
5409                 assert!(node_txn.is_empty());
5410                 res
5411         }
5412
5413         /// Tests that the given node has broadcast a claim transaction against the provided revoked
5414         /// HTLC transaction.
5415         fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
5416                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5417                 assert_eq!(node_txn.len(), 1);
5418                 node_txn.retain(|tx| {
5419                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
5420                                 check_spends!(tx, revoked_tx.clone());
5421                                 false
5422                         } else { true }
5423                 });
5424                 assert!(node_txn.is_empty());
5425         }
5426
5427         fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
5428                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5429
5430                 assert!(node_txn.len() >= 1);
5431                 assert_eq!(node_txn[0].input.len(), 1);
5432                 let mut found_prev = false;
5433
5434                 for tx in prev_txn {
5435                         if node_txn[0].input[0].previous_output.txid == tx.txid() {
5436                                 check_spends!(node_txn[0], tx.clone());
5437                                 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
5438                                 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
5439
5440                                 found_prev = true;
5441                                 break;
5442                         }
5443                 }
5444                 assert!(found_prev);
5445
5446                 let mut res = Vec::new();
5447                 mem::swap(&mut *node_txn, &mut res);
5448                 res
5449         }
5450
5451         fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
5452                 let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
5453                 assert_eq!(events_1.len(), 1);
5454                 let as_update = match events_1[0] {
5455                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5456                                 msg.clone()
5457                         },
5458                         _ => panic!("Unexpected event"),
5459                 };
5460
5461                 let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
5462                 assert_eq!(events_2.len(), 1);
5463                 let bs_update = match events_2[0] {
5464                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5465                                 msg.clone()
5466                         },
5467                         _ => panic!("Unexpected event"),
5468                 };
5469
5470                 for node in nodes {
5471                         node.router.handle_channel_update(&as_update).unwrap();
5472                         node.router.handle_channel_update(&bs_update).unwrap();
5473                 }
5474         }
5475
5476         macro_rules! expect_pending_htlcs_forwardable {
5477                 ($node: expr) => {{
5478                         let events = $node.node.get_and_clear_pending_events();
5479                         assert_eq!(events.len(), 1);
5480                         match events[0] {
5481                                 Event::PendingHTLCsForwardable { .. } => { },
5482                                 _ => panic!("Unexpected event"),
5483                         };
5484                         $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
5485                         $node.node.process_pending_htlc_forwards();
5486                 }}
5487         }
5488
5489         fn do_channel_reserve_test(test_recv: bool) {
5490                 use util::rng;
5491                 use std::sync::atomic::Ordering;
5492                 use ln::msgs::HandleError;
5493
5494                 macro_rules! get_channel_value_stat {
5495                         ($node: expr, $channel_id: expr) => {{
5496                                 let chan_lock = $node.node.channel_state.lock().unwrap();
5497                                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
5498                                 chan.get_value_stat()
5499                         }}
5500                 }
5501
5502                 let mut nodes = create_network(3);
5503                 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001);
5504                 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001);
5505
5506                 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
5507                 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
5508
5509                 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
5510                 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
5511
5512                 macro_rules! get_route_and_payment_hash {
5513                         ($recv_value: expr) => {{
5514                                 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
5515                                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5516                                 (route, payment_hash, payment_preimage)
5517                         }}
5518                 };
5519
5520                 macro_rules! expect_forward {
5521                         ($node: expr) => {{
5522                                 let mut events = $node.node.get_and_clear_pending_msg_events();
5523                                 assert_eq!(events.len(), 1);
5524                                 check_added_monitors!($node, 1);
5525                                 let payment_event = SendEvent::from_event(events.remove(0));
5526                                 payment_event
5527                         }}
5528                 }
5529
5530                 macro_rules! expect_payment_received {
5531                         ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
5532                                 let events = $node.node.get_and_clear_pending_events();
5533                                 assert_eq!(events.len(), 1);
5534                                 match events[0] {
5535                                         Event::PaymentReceived { ref payment_hash, amt } => {
5536                                                 assert_eq!($expected_payment_hash, *payment_hash);
5537                                                 assert_eq!($expected_recv_value, amt);
5538                                         },
5539                                         _ => panic!("Unexpected event"),
5540                                 }
5541                         }
5542                 };
5543
5544                 let feemsat = 239; // somehow we know?
5545                 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
5546
5547                 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
5548
5549                 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
5550                 {
5551                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
5552                         assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
5553                         let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
5554                         match err {
5555                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
5556                                 _ => panic!("Unknown error variants"),
5557                         }
5558                 }
5559
5560                 let mut htlc_id = 0;
5561                 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
5562                 // nodes[0]'s wealth
5563                 loop {
5564                         let amt_msat = recv_value_0 + total_fee_msat;
5565                         if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
5566                                 break;
5567                         }
5568                         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
5569                         htlc_id += 1;
5570
5571                         let (stat01_, stat11_, stat12_, stat22_) = (
5572                                 get_channel_value_stat!(nodes[0], chan_1.2),
5573                                 get_channel_value_stat!(nodes[1], chan_1.2),
5574                                 get_channel_value_stat!(nodes[1], chan_2.2),
5575                                 get_channel_value_stat!(nodes[2], chan_2.2),
5576                         );
5577
5578                         assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
5579                         assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
5580                         assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
5581                         assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
5582                         stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
5583                 }
5584
5585                 {
5586                         let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
5587                         // attempt to get channel_reserve violation
5588                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
5589                         let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
5590                         match err {
5591                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5592                                 _ => panic!("Unknown error variants"),
5593                         }
5594                 }
5595
5596                 // adding pending output
5597                 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
5598                 let amt_msat_1 = recv_value_1 + total_fee_msat;
5599
5600                 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
5601                 let payment_event_1 = {
5602                         nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
5603                         check_added_monitors!(nodes[0], 1);
5604
5605                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5606                         assert_eq!(events.len(), 1);
5607                         SendEvent::from_event(events.remove(0))
5608                 };
5609                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]).unwrap();
5610
5611                 // channel reserve test with htlc pending output > 0
5612                 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
5613                 {
5614                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5615                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5616                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5617                                 _ => panic!("Unknown error variants"),
5618                         }
5619                 }
5620
5621                 {
5622                         // test channel_reserve test on nodes[1] side
5623                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5624
5625                         // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
5626                         let secp_ctx = Secp256k1::new();
5627                         let session_priv = SecretKey::from_slice(&secp_ctx, &{
5628                                 let mut session_key = [0; 32];
5629                                 rng::fill_bytes(&mut session_key);
5630                                 session_key
5631                         }).expect("RNG is bad!");
5632
5633                         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5634                         let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
5635                         let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height).unwrap();
5636                         let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
5637                         let msg = msgs::UpdateAddHTLC {
5638                                 channel_id: chan_1.2,
5639                                 htlc_id,
5640                                 amount_msat: htlc_msat,
5641                                 payment_hash: our_payment_hash,
5642                                 cltv_expiry: htlc_cltv,
5643                                 onion_routing_packet: onion_packet,
5644                         };
5645
5646                         if test_recv {
5647                                 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).err().unwrap();
5648                                 match err {
5649                                         HandleError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
5650                                 }
5651                                 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
5652                                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5653                                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5654                                 let channel_close_broadcast = nodes[1].node.get_and_clear_pending_msg_events();
5655                                 assert_eq!(channel_close_broadcast.len(), 1);
5656                                 match channel_close_broadcast[0] {
5657                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5658                                                 assert_eq!(msg.contents.flags & 2, 2);
5659                                         },
5660                                         _ => panic!("Unexpected event"),
5661                                 }
5662                                 return;
5663                         }
5664                 }
5665
5666                 // split the rest to test holding cell
5667                 let recv_value_21 = recv_value_2/2;
5668                 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
5669                 {
5670                         let stat = get_channel_value_stat!(nodes[0], chan_1.2);
5671                         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);
5672                 }
5673
5674                 // now see if they go through on both sides
5675                 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
5676                 // but this will stuck in the holding cell
5677                 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
5678                 check_added_monitors!(nodes[0], 0);
5679                 let events = nodes[0].node.get_and_clear_pending_events();
5680                 assert_eq!(events.len(), 0);
5681
5682                 // test with outbound holding cell amount > 0
5683                 {
5684                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
5685                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5686                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5687                                 _ => panic!("Unknown error variants"),
5688                         }
5689                 }
5690
5691                 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
5692                 // this will also stuck in the holding cell
5693                 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
5694                 check_added_monitors!(nodes[0], 0);
5695                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
5696                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5697
5698                 // flush the pending htlc
5699                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg).unwrap();
5700                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5701                 check_added_monitors!(nodes[1], 1);
5702
5703                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
5704                 check_added_monitors!(nodes[0], 1);
5705                 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5706
5707                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed).unwrap();
5708                 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
5709                 // No commitment_signed so get_event_msg's assert(len == 1) passes
5710                 check_added_monitors!(nodes[0], 1);
5711
5712                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
5713                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5714                 check_added_monitors!(nodes[1], 1);
5715
5716                 expect_pending_htlcs_forwardable!(nodes[1]);
5717
5718                 let ref payment_event_11 = expect_forward!(nodes[1]);
5719                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]).unwrap();
5720                 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
5721
5722                 expect_pending_htlcs_forwardable!(nodes[2]);
5723                 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
5724
5725                 // flush the htlcs in the holding cell
5726                 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
5727                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]).unwrap();
5728                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]).unwrap();
5729                 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
5730                 expect_pending_htlcs_forwardable!(nodes[1]);
5731
5732                 let ref payment_event_3 = expect_forward!(nodes[1]);
5733                 assert_eq!(payment_event_3.msgs.len(), 2);
5734                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]).unwrap();
5735                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]).unwrap();
5736
5737                 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
5738                 expect_pending_htlcs_forwardable!(nodes[2]);
5739
5740                 let events = nodes[2].node.get_and_clear_pending_events();
5741                 assert_eq!(events.len(), 2);
5742                 match events[0] {
5743                         Event::PaymentReceived { ref payment_hash, amt } => {
5744                                 assert_eq!(our_payment_hash_21, *payment_hash);
5745                                 assert_eq!(recv_value_21, amt);
5746                         },
5747                         _ => panic!("Unexpected event"),
5748                 }
5749                 match events[1] {
5750                         Event::PaymentReceived { ref payment_hash, amt } => {
5751                                 assert_eq!(our_payment_hash_22, *payment_hash);
5752                                 assert_eq!(recv_value_22, amt);
5753                         },
5754                         _ => panic!("Unexpected event"),
5755                 }
5756
5757                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
5758                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
5759                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
5760
5761                 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);
5762                 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
5763                 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
5764                 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
5765
5766                 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
5767                 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
5768         }
5769
5770         #[test]
5771         fn channel_reserve_test() {
5772                 do_channel_reserve_test(false);
5773                 do_channel_reserve_test(true);
5774         }
5775
5776         #[test]
5777         fn channel_monitor_network_test() {
5778                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5779                 // tests that ChannelMonitor is able to recover from various states.
5780                 let nodes = create_network(5);
5781
5782                 // Create some initial channels
5783                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5784                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5785                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5786                 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5787
5788                 // Rebalance the network a bit by relaying one payment through all the channels...
5789                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5790                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5791                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5792                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5793
5794                 // Simple case with no pending HTLCs:
5795                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
5796                 {
5797                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
5798                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5799                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5800                         test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
5801                 }
5802                 get_announce_close_broadcast_events(&nodes, 0, 1);
5803                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5804                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5805
5806                 // One pending HTLC is discarded by the force-close:
5807                 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
5808
5809                 // Simple case of one pending HTLC to HTLC-Timeout
5810                 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
5811                 {
5812                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
5813                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5814                         nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5815                         test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
5816                 }
5817                 get_announce_close_broadcast_events(&nodes, 1, 2);
5818                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5819                 assert_eq!(nodes[2].node.list_channels().len(), 1);
5820
5821                 macro_rules! claim_funds {
5822                         ($node: expr, $prev_node: expr, $preimage: expr) => {
5823                                 {
5824                                         assert!($node.node.claim_funds($preimage));
5825                                         check_added_monitors!($node, 1);
5826
5827                                         let events = $node.node.get_and_clear_pending_msg_events();
5828                                         assert_eq!(events.len(), 1);
5829                                         match events[0] {
5830                                                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
5831                                                         assert!(update_add_htlcs.is_empty());
5832                                                         assert!(update_fail_htlcs.is_empty());
5833                                                         assert_eq!(*node_id, $prev_node.node.get_our_node_id());
5834                                                 },
5835                                                 _ => panic!("Unexpected event"),
5836                                         };
5837                                 }
5838                         }
5839                 }
5840
5841                 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
5842                 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
5843                 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
5844                 {
5845                         let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
5846
5847                         // Claim the payment on nodes[3], giving it knowledge of the preimage
5848                         claim_funds!(nodes[3], nodes[2], payment_preimage_1);
5849
5850                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5851                         nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
5852
5853                         check_preimage_claim(&nodes[3], &node_txn);
5854                 }
5855                 get_announce_close_broadcast_events(&nodes, 2, 3);
5856                 assert_eq!(nodes[2].node.list_channels().len(), 0);
5857                 assert_eq!(nodes[3].node.list_channels().len(), 1);
5858
5859                 { // Cheat and reset nodes[4]'s height to 1
5860                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5861                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![] }, 1);
5862                 }
5863
5864                 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
5865                 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
5866                 // One pending HTLC to time out:
5867                 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
5868                 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
5869                 // buffer space).
5870
5871                 {
5872                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5873                         nodes[3].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5874                         for i in 3..TEST_FINAL_CLTV + 2 + HTLC_FAIL_TIMEOUT_BLOCKS + 1 {
5875                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5876                                 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5877                         }
5878
5879                         let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
5880
5881                         // Claim the payment on nodes[4], giving it knowledge of the preimage
5882                         claim_funds!(nodes[4], nodes[3], payment_preimage_2);
5883
5884                         header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5885                         nodes[4].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5886                         for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
5887                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5888                                 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5889                         }
5890
5891                         test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
5892
5893                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5894                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
5895
5896                         check_preimage_claim(&nodes[4], &node_txn);
5897                 }
5898                 get_announce_close_broadcast_events(&nodes, 3, 4);
5899                 assert_eq!(nodes[3].node.list_channels().len(), 0);
5900                 assert_eq!(nodes[4].node.list_channels().len(), 0);
5901         }
5902
5903         #[test]
5904         fn test_justice_tx() {
5905                 // Test justice txn built on revoked HTLC-Success tx, against both sides
5906
5907                 let nodes = create_network(2);
5908                 // Create some new channels:
5909                 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
5910
5911                 // A pending HTLC which will be revoked:
5912                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5913                 // Get the will-be-revoked local txn from nodes[0]
5914                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5915                 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
5916                 assert_eq!(revoked_local_txn[0].input.len(), 1);
5917                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
5918                 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
5919                 assert_eq!(revoked_local_txn[1].input.len(), 1);
5920                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
5921                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
5922                 // Revoke the old state
5923                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
5924
5925                 {
5926                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5927                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5928                         {
5929                                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5930                                 assert_eq!(node_txn.len(), 3);
5931                                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5932                                 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
5933
5934                                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5935                                 node_txn.swap_remove(0);
5936                         }
5937                         test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
5938
5939                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5940                         let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
5941                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5942                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5943                         test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
5944                 }
5945                 get_announce_close_broadcast_events(&nodes, 0, 1);
5946
5947                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5948                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5949
5950                 // We test justice_tx build by A on B's revoked HTLC-Success tx
5951                 // Create some new channels:
5952                 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
5953
5954                 // A pending HTLC which will be revoked:
5955                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5956                 // Get the will-be-revoked local txn from B
5957                 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5958                 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
5959                 assert_eq!(revoked_local_txn[0].input.len(), 1);
5960                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
5961                 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
5962                 // Revoke the old state
5963                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
5964                 {
5965                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5966                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5967                         {
5968                                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5969                                 assert_eq!(node_txn.len(), 3);
5970                                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5971                                 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
5972
5973                                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5974                                 node_txn.swap_remove(0);
5975                         }
5976                         test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
5977
5978                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5979                         let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
5980                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5981                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5982                         test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone());
5983                 }
5984                 get_announce_close_broadcast_events(&nodes, 0, 1);
5985                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5986                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5987         }
5988
5989         #[test]
5990         fn revoked_output_claim() {
5991                 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
5992                 // transaction is broadcast by its counterparty
5993                 let nodes = create_network(2);
5994                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5995                 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
5996                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5997                 assert_eq!(revoked_local_txn.len(), 1);
5998                 // Only output is the full channel value back to nodes[0]:
5999                 assert_eq!(revoked_local_txn[0].output.len(), 1);
6000                 // Send a payment through, updating everyone's latest commitment txn
6001                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
6002
6003                 // Inform nodes[1] that nodes[0] broadcast a stale tx
6004                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6005                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6006                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6007                 assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
6008
6009                 assert_eq!(node_txn[0], node_txn[2]);
6010
6011                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
6012                 check_spends!(node_txn[1], chan_1.3.clone());
6013
6014                 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
6015                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6016                 get_announce_close_broadcast_events(&nodes, 0, 1);
6017         }
6018
6019         #[test]
6020         fn claim_htlc_outputs_shared_tx() {
6021                 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
6022                 let nodes = create_network(2);
6023
6024                 // Create some new channel:
6025                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6026
6027                 // Rebalance the network to generate htlc in the two directions
6028                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6029                 // 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
6030                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6031                 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6032
6033                 // Get the will-be-revoked local txn from node[0]
6034                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6035                 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
6036                 assert_eq!(revoked_local_txn[0].input.len(), 1);
6037                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
6038                 assert_eq!(revoked_local_txn[1].input.len(), 1);
6039                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
6040                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
6041                 check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
6042
6043                 //Revoke the old state
6044                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6045
6046                 {
6047                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6048                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6049                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6050
6051                         let events = nodes[1].node.get_and_clear_pending_events();
6052                         assert_eq!(events.len(), 1);
6053                         match events[0] {
6054                                 Event::PaymentFailed { payment_hash, .. } => {
6055                                         assert_eq!(payment_hash, payment_hash_2);
6056                                 },
6057                                 _ => panic!("Unexpected event"),
6058                         }
6059
6060                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6061                         assert_eq!(node_txn.len(), 4);
6062
6063                         assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
6064                         check_spends!(node_txn[0], revoked_local_txn[0].clone());
6065
6066                         assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
6067
6068                         let mut witness_lens = BTreeSet::new();
6069                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6070                         witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
6071                         witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
6072                         assert_eq!(witness_lens.len(), 3);
6073                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6074                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
6075                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
6076
6077                         // Next nodes[1] broadcasts its current local tx state:
6078                         assert_eq!(node_txn[1].input.len(), 1);
6079                         assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
6080
6081                         assert_eq!(node_txn[2].input.len(), 1);
6082                         let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
6083                         assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
6084                         assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
6085                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6086                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
6087                 }
6088                 get_announce_close_broadcast_events(&nodes, 0, 1);
6089                 assert_eq!(nodes[0].node.list_channels().len(), 0);
6090                 assert_eq!(nodes[1].node.list_channels().len(), 0);
6091         }
6092
6093         #[test]
6094         fn claim_htlc_outputs_single_tx() {
6095                 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
6096                 let nodes = create_network(2);
6097
6098                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6099
6100                 // Rebalance the network to generate htlc in the two directions
6101                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6102                 // 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
6103                 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
6104                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6105                 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6106
6107                 // Get the will-be-revoked local txn from node[0]
6108                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6109
6110                 //Revoke the old state
6111                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6112
6113                 {
6114                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6115                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6116                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6117
6118                         let events = nodes[1].node.get_and_clear_pending_events();
6119                         assert_eq!(events.len(), 1);
6120                         match events[0] {
6121                                 Event::PaymentFailed { payment_hash, .. } => {
6122                                         assert_eq!(payment_hash, payment_hash_2);
6123                                 },
6124                                 _ => panic!("Unexpected event"),
6125                         }
6126
6127                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6128                         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)
6129
6130                         assert_eq!(node_txn[0], node_txn[7]);
6131                         assert_eq!(node_txn[1], node_txn[8]);
6132                         assert_eq!(node_txn[2], node_txn[9]);
6133                         assert_eq!(node_txn[3], node_txn[10]);
6134                         assert_eq!(node_txn[4], node_txn[11]);
6135                         assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcated by ChannelManger
6136                         assert_eq!(node_txn[4], node_txn[6]);
6137
6138                         assert_eq!(node_txn[0].input.len(), 1);
6139                         assert_eq!(node_txn[1].input.len(), 1);
6140                         assert_eq!(node_txn[2].input.len(), 1);
6141
6142                         let mut revoked_tx_map = HashMap::new();
6143                         revoked_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
6144                         node_txn[0].verify(&revoked_tx_map).unwrap();
6145                         node_txn[1].verify(&revoked_tx_map).unwrap();
6146                         node_txn[2].verify(&revoked_tx_map).unwrap();
6147
6148                         let mut witness_lens = BTreeSet::new();
6149                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6150                         witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
6151                         witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
6152                         assert_eq!(witness_lens.len(), 3);
6153                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6154                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
6155                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
6156
6157                         assert_eq!(node_txn[3].input.len(), 1);
6158                         check_spends!(node_txn[3], chan_1.3.clone());
6159
6160                         assert_eq!(node_txn[4].input.len(), 1);
6161                         let witness_script = node_txn[4].input[0].witness.last().unwrap();
6162                         assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
6163                         assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
6164                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6165                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
6166                 }
6167                 get_announce_close_broadcast_events(&nodes, 0, 1);
6168                 assert_eq!(nodes[0].node.list_channels().len(), 0);
6169                 assert_eq!(nodes[1].node.list_channels().len(), 0);
6170         }
6171
6172         #[test]
6173         fn test_htlc_on_chain_success() {
6174                 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
6175                 // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
6176                 // broadcasting the right event to other nodes in payment path.
6177                 // A --------------------> B ----------------------> C (preimage)
6178                 // First, C should claim the HTLC output via HTLC-Success when its own latest local
6179                 // commitment transaction was broadcast.
6180                 // Then, B should learn the preimage from said transactions, attempting to claim backwards
6181                 // towards B.
6182                 // B should be able to claim via preimage if A then broadcasts its local tx.
6183                 // Finally, when A sees B's latest local commitment transaction it should be able to claim
6184                 // the HTLC output via the preimage it learned (which, once confirmed should generate a
6185                 // PaymentSent event).
6186
6187                 let nodes = create_network(3);
6188
6189                 // Create some initial channels
6190                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6191                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6192
6193                 // Rebalance the network a bit by relaying one payment through all the channels...
6194                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6195                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6196
6197                 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
6198                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6199
6200                 // Broadcast legit commitment tx from C on B's chain
6201                 // Broadcast HTLC Success transation by C on received output from C's commitment tx on B's chain
6202                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6203                 assert_eq!(commitment_tx.len(), 1);
6204                 check_spends!(commitment_tx[0], chan_2.3.clone());
6205                 nodes[2].node.claim_funds(our_payment_preimage);
6206                 check_added_monitors!(nodes[2], 1);
6207                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6208                 assert!(updates.update_add_htlcs.is_empty());
6209                 assert!(updates.update_fail_htlcs.is_empty());
6210                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6211                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
6212
6213                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6214                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6215                 assert_eq!(events.len(), 1);
6216                 match events[0] {
6217                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6218                         _ => panic!("Unexpected event"),
6219                 }
6220                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
6221                 assert_eq!(node_txn.len(), 3);
6222                 assert_eq!(node_txn[1], commitment_tx[0]);
6223                 assert_eq!(node_txn[0], node_txn[2]);
6224                 check_spends!(node_txn[0], commitment_tx[0].clone());
6225                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6226                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6227                 assert_eq!(node_txn[0].lock_time, 0);
6228
6229                 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
6230                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: node_txn}, 1);
6231                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6232                 {
6233                         let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
6234                         assert_eq!(added_monitors.len(), 1);
6235                         assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
6236                         added_monitors.clear();
6237                 }
6238                 assert_eq!(events.len(), 2);
6239                 match events[0] {
6240                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6241                         _ => panic!("Unexpected event"),
6242                 }
6243                 match events[1] {
6244                         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, .. } } => {
6245                                 assert!(update_add_htlcs.is_empty());
6246                                 assert!(update_fail_htlcs.is_empty());
6247                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6248                                 assert!(update_fail_malformed_htlcs.is_empty());
6249                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6250                         },
6251                         _ => panic!("Unexpected event"),
6252                 };
6253                 {
6254                         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
6255                         // commitment transaction with a corresponding HTLC-Timeout transaction, as well as a
6256                         // timeout-claim of the output that nodes[2] just claimed via success.
6257                         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)
6258                         assert_eq!(node_txn.len(), 4);
6259                         assert_eq!(node_txn[0], node_txn[3]);
6260                         check_spends!(node_txn[0], commitment_tx[0].clone());
6261                         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6262                         assert_ne!(node_txn[0].lock_time, 0);
6263                         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
6264                         check_spends!(node_txn[1], chan_2.3.clone());
6265                         check_spends!(node_txn[2], node_txn[1].clone());
6266                         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6267                         assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6268                         assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6269                         assert_ne!(node_txn[2].lock_time, 0);
6270                         node_txn.clear();
6271                 }
6272
6273                 // Broadcast legit commitment tx from A on B's chain
6274                 // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
6275                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6276                 check_spends!(commitment_tx[0], chan_1.3.clone());
6277                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6278                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6279                 assert_eq!(events.len(), 1);
6280                 match events[0] {
6281                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6282                         _ => panic!("Unexpected event"),
6283                 }
6284                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 1 (HTLC-Success) * 2 (block-rescan)
6285                 assert_eq!(node_txn.len(), 3);
6286                 assert_eq!(node_txn[0], node_txn[2]);
6287                 check_spends!(node_txn[0], commitment_tx[0].clone());
6288                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6289                 assert_eq!(node_txn[0].lock_time, 0);
6290                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
6291                 check_spends!(node_txn[1], chan_1.3.clone());
6292                 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6293                 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
6294                 // we already checked the same situation with A.
6295
6296                 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
6297                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
6298                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6299                 assert_eq!(events.len(), 1);
6300                 match events[0] {
6301                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6302                         _ => panic!("Unexpected event"),
6303                 }
6304                 let events = nodes[0].node.get_and_clear_pending_events();
6305                 assert_eq!(events.len(), 1);
6306                 match events[0] {
6307                         Event::PaymentSent { payment_preimage } => {
6308                                 assert_eq!(payment_preimage, our_payment_preimage);
6309                         },
6310                         _ => panic!("Unexpected event"),
6311                 }
6312                 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)
6313                 assert_eq!(node_txn.len(), 4);
6314                 assert_eq!(node_txn[0], node_txn[3]);
6315                 check_spends!(node_txn[0], commitment_tx[0].clone());
6316                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6317                 assert_ne!(node_txn[0].lock_time, 0);
6318                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6319                 check_spends!(node_txn[1], chan_1.3.clone());
6320                 check_spends!(node_txn[2], node_txn[1].clone());
6321                 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6322                 assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6323                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6324                 assert_ne!(node_txn[2].lock_time, 0);
6325         }
6326
6327         #[test]
6328         fn test_htlc_on_chain_timeout() {
6329                 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
6330                 // ChainWatchInterface and timeout the HTLC  bacward accordingly. So here we test that ChannelManager is
6331                 // broadcasting the right event to other nodes in payment path.
6332                 // A ------------------> B ----------------------> C (timeout)
6333                 //    B's commitment tx                 C's commitment tx
6334                 //            \                                  \
6335                 //         B's HTLC timeout tx               B's timeout tx
6336
6337                 let nodes = create_network(3);
6338
6339                 // Create some intial channels
6340                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6341                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6342
6343                 // Rebalance the network a bit by relaying one payment thorugh all the channels...
6344                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6345                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6346
6347                 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
6348                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6349
6350                 // Brodacast legit commitment tx from C on B's chain
6351                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6352                 check_spends!(commitment_tx[0], chan_2.3.clone());
6353                 nodes[2].node.fail_htlc_backwards(&payment_hash, PaymentFailReason::PreimageUnknown);
6354                 {
6355                         let mut added_monitors = nodes[2].chan_monitor.added_monitors.lock().unwrap();
6356                         assert_eq!(added_monitors.len(), 1);
6357                         added_monitors.clear();
6358                 }
6359                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6360                 assert_eq!(events.len(), 1);
6361                 match events[0] {
6362                         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, .. } } => {
6363                                 assert!(update_add_htlcs.is_empty());
6364                                 assert!(!update_fail_htlcs.is_empty());
6365                                 assert!(update_fulfill_htlcs.is_empty());
6366                                 assert!(update_fail_malformed_htlcs.is_empty());
6367                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
6368                         },
6369                         _ => panic!("Unexpected event"),
6370                 };
6371                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6372                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6373                 assert_eq!(events.len(), 1);
6374                 match events[0] {
6375                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6376                         _ => panic!("Unexpected event"),
6377                 }
6378                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
6379                 assert_eq!(node_txn.len(), 1);
6380                 check_spends!(node_txn[0], chan_2.3.clone());
6381                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
6382
6383                 // Broadcast timeout transaction by B on received output fron C's commitment tx on B's chain
6384                 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
6385                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6386                 let timeout_tx;
6387                 {
6388                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6389                         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)
6390                         assert_eq!(node_txn[0], node_txn[5]);
6391                         assert_eq!(node_txn[1], node_txn[6]);
6392                         assert_eq!(node_txn[2], node_txn[7]);
6393                         check_spends!(node_txn[0], commitment_tx[0].clone());
6394                         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6395                         check_spends!(node_txn[1], chan_2.3.clone());
6396                         check_spends!(node_txn[2], node_txn[1].clone());
6397                         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6398                         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6399                         check_spends!(node_txn[3], chan_2.3.clone());
6400                         check_spends!(node_txn[4], node_txn[3].clone());
6401                         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
6402                         assert_eq!(node_txn[4].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6403                         timeout_tx = node_txn[0].clone();
6404                         node_txn.clear();
6405                 }
6406
6407                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![timeout_tx]}, 1);
6408                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6409                 check_added_monitors!(nodes[1], 1);
6410                 assert_eq!(events.len(), 2);
6411                 match events[0] {
6412                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6413                         _ => panic!("Unexpected event"),
6414                 }
6415                 match events[1] {
6416                         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, .. } } => {
6417                                 assert!(update_add_htlcs.is_empty());
6418                                 assert!(!update_fail_htlcs.is_empty());
6419                                 assert!(update_fulfill_htlcs.is_empty());
6420                                 assert!(update_fail_malformed_htlcs.is_empty());
6421                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6422                         },
6423                         _ => panic!("Unexpected event"),
6424                 };
6425                 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
6426                 assert_eq!(node_txn.len(), 0);
6427
6428                 // Broadcast legit commitment tx from B on A's chain
6429                 let commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6430                 check_spends!(commitment_tx[0], chan_1.3.clone());
6431
6432                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6433                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6434                 assert_eq!(events.len(), 1);
6435                 match events[0] {
6436                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6437                         _ => panic!("Unexpected event"),
6438                 }
6439                 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
6440                 assert_eq!(node_txn.len(), 4);
6441                 assert_eq!(node_txn[0], node_txn[3]);
6442                 check_spends!(node_txn[0], commitment_tx[0].clone());
6443                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6444                 check_spends!(node_txn[1], chan_1.3.clone());
6445                 check_spends!(node_txn[2], node_txn[1].clone());
6446                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6447                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6448         }
6449
6450         #[test]
6451         fn test_simple_commitment_revoked_fail_backward() {
6452                 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
6453                 // and fail backward accordingly.
6454
6455                 let nodes = create_network(3);
6456
6457                 // Create some initial channels
6458                 create_announced_chan_between_nodes(&nodes, 0, 1);
6459                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6460
6461                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6462                 // Get the will-be-revoked local txn from nodes[2]
6463                 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6464                 // Revoke the old state
6465                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6466
6467                 route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6468
6469                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6470                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6471                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6472                 check_added_monitors!(nodes[1], 1);
6473                 assert_eq!(events.len(), 2);
6474                 match events[0] {
6475                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6476                         _ => panic!("Unexpected event"),
6477                 }
6478                 match events[1] {
6479                         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, .. } } => {
6480                                 assert!(update_add_htlcs.is_empty());
6481                                 assert_eq!(update_fail_htlcs.len(), 1);
6482                                 assert!(update_fulfill_htlcs.is_empty());
6483                                 assert!(update_fail_malformed_htlcs.is_empty());
6484                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6485
6486                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6487                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6488
6489                                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6490                                 assert_eq!(events.len(), 1);
6491                                 match events[0] {
6492                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6493                                         _ => panic!("Unexpected event"),
6494                                 }
6495                                 let events = nodes[0].node.get_and_clear_pending_events();
6496                                 assert_eq!(events.len(), 1);
6497                                 match events[0] {
6498                                         Event::PaymentFailed { .. } => {},
6499                                         _ => panic!("Unexpected event"),
6500                                 }
6501                         },
6502                         _ => panic!("Unexpected event"),
6503                 }
6504         }
6505
6506         fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool) {
6507                 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
6508                 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
6509                 // commitment transaction anymore.
6510                 // To do this, we have the peer which will broadcast a revoked commitment transaction send
6511                 // a number of update_fail/commitment_signed updates without ever sending the RAA in
6512                 // response to our commitment_signed. This is somewhat misbehavior-y, though not
6513                 // technically disallowed and we should probably handle it reasonably.
6514                 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
6515                 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
6516                 // transactions:
6517                 // * Once we move it out of our holding cell/add it, we will immediately include it in a
6518                 //   commitment_signed (implying it will be in the latest remote commitment transaction).
6519                 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
6520                 //   and once they revoke the previous commitment transaction (allowing us to send a new
6521                 //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
6522                 let mut nodes = create_network(3);
6523
6524                 // Create some initial channels
6525                 create_announced_chan_between_nodes(&nodes, 0, 1);
6526                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6527
6528                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6529                 // Get the will-be-revoked local txn from nodes[2]
6530                 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6531                 // Revoke the old state
6532                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6533
6534                 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6535                 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6536                 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6537
6538                 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, PaymentFailReason::PreimageUnknown));
6539                 check_added_monitors!(nodes[2], 1);
6540                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6541                 assert!(updates.update_add_htlcs.is_empty());
6542                 assert!(updates.update_fulfill_htlcs.is_empty());
6543                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6544                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6545                 assert!(updates.update_fee.is_none());
6546                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6547                 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
6548                 // Drop the last RAA from 3 -> 2
6549
6550                 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, PaymentFailReason::PreimageUnknown));
6551                 check_added_monitors!(nodes[2], 1);
6552                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6553                 assert!(updates.update_add_htlcs.is_empty());
6554                 assert!(updates.update_fulfill_htlcs.is_empty());
6555                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6556                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6557                 assert!(updates.update_fee.is_none());
6558                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6559                 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6560                 check_added_monitors!(nodes[1], 1);
6561                 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
6562                 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6563                 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6564                 check_added_monitors!(nodes[2], 1);
6565
6566                 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, PaymentFailReason::PreimageUnknown));
6567                 check_added_monitors!(nodes[2], 1);
6568                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6569                 assert!(updates.update_add_htlcs.is_empty());
6570                 assert!(updates.update_fulfill_htlcs.is_empty());
6571                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6572                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6573                 assert!(updates.update_fee.is_none());
6574                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6575                 // At this point first_payment_hash has dropped out of the latest two commitment
6576                 // transactions that nodes[1] is tracking...
6577                 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6578                 check_added_monitors!(nodes[1], 1);
6579                 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
6580                 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6581                 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6582                 check_added_monitors!(nodes[2], 1);
6583
6584                 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
6585                 // on nodes[2]'s RAA.
6586                 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
6587                 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6588                 nodes[1].node.send_payment(route, fourth_payment_hash).unwrap();
6589                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
6590                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6591                 check_added_monitors!(nodes[1], 0);
6592
6593                 if deliver_bs_raa {
6594                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa).unwrap();
6595                         // One monitor for the new revocation preimage, one as we generate a commitment for
6596                         // nodes[0] to fail first_payment_hash backwards.
6597                         check_added_monitors!(nodes[1], 2);
6598                 }
6599
6600                 let mut failed_htlcs = HashSet::new();
6601                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6602
6603                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6604                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6605
6606                 let events = nodes[1].node.get_and_clear_pending_events();
6607                 assert_eq!(events.len(), 1);
6608                 match events[0] {
6609                         Event::PaymentFailed { ref payment_hash, .. } => {
6610                                 assert_eq!(*payment_hash, fourth_payment_hash);
6611                         },
6612                         _ => panic!("Unexpected event"),
6613                 }
6614
6615                 if !deliver_bs_raa {
6616                         // If we delivered the RAA already then we already failed first_payment_hash backwards.
6617                         check_added_monitors!(nodes[1], 1);
6618                 }
6619
6620                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6621                 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
6622                 match events[if deliver_bs_raa { 2 } else { 0 }] {
6623                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6624                         _ => panic!("Unexpected event"),
6625                 }
6626                 if deliver_bs_raa {
6627                         match events[0] {
6628                                 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, .. } } => {
6629                                         assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
6630                                         assert_eq!(update_add_htlcs.len(), 1);
6631                                         assert!(update_fulfill_htlcs.is_empty());
6632                                         assert!(update_fail_htlcs.is_empty());
6633                                         assert!(update_fail_malformed_htlcs.is_empty());
6634                                 },
6635                                 _ => panic!("Unexpected event"),
6636                         }
6637                 }
6638                 // Due to the way backwards-failing occurs we do the updates in two steps.
6639                 let updates = match events[1] {
6640                         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, .. } } => {
6641                                 assert!(update_add_htlcs.is_empty());
6642                                 assert_eq!(update_fail_htlcs.len(), 1);
6643                                 assert!(update_fulfill_htlcs.is_empty());
6644                                 assert!(update_fail_malformed_htlcs.is_empty());
6645                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6646
6647                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6648                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
6649                                 check_added_monitors!(nodes[0], 1);
6650                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6651                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6652                                 check_added_monitors!(nodes[1], 1);
6653                                 let bs_second_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6654                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
6655                                 check_added_monitors!(nodes[1], 1);
6656                                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6657                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6658                                 check_added_monitors!(nodes[0], 1);
6659
6660                                 if !deliver_bs_raa {
6661                                         // If we delievered B's RAA we got an unknown preimage error, not something
6662                                         // that we should update our routing table for.
6663                                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6664                                         assert_eq!(events.len(), 1);
6665                                         match events[0] {
6666                                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6667                                                 _ => panic!("Unexpected event"),
6668                                         }
6669                                 }
6670                                 let events = nodes[0].node.get_and_clear_pending_events();
6671                                 assert_eq!(events.len(), 1);
6672                                 match events[0] {
6673                                         Event::PaymentFailed { ref payment_hash, .. } => {
6674                                                 assert!(failed_htlcs.insert(payment_hash.0));
6675                                         },
6676                                         _ => panic!("Unexpected event"),
6677                                 }
6678
6679                                 bs_second_update
6680                         },
6681                         _ => panic!("Unexpected event"),
6682                 };
6683
6684                 assert!(updates.update_add_htlcs.is_empty());
6685                 assert_eq!(updates.update_fail_htlcs.len(), 2);
6686                 assert!(updates.update_fulfill_htlcs.is_empty());
6687                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6688                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6689                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[1]).unwrap();
6690                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6691
6692                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6693                 assert_eq!(events.len(), 2);
6694                 for event in events {
6695                         match event {
6696                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6697                                 _ => panic!("Unexpected event"),
6698                         }
6699                 }
6700
6701                 let events = nodes[0].node.get_and_clear_pending_events();
6702                 assert_eq!(events.len(), 2);
6703                 match events[0] {
6704                         Event::PaymentFailed { ref payment_hash, .. } => {
6705                                 assert!(failed_htlcs.insert(payment_hash.0));
6706                         },
6707                         _ => panic!("Unexpected event"),
6708                 }
6709                 match events[1] {
6710                         Event::PaymentFailed { ref payment_hash, .. } => {
6711                                 assert!(failed_htlcs.insert(payment_hash.0));
6712                         },
6713                         _ => panic!("Unexpected event"),
6714                 }
6715
6716                 assert!(failed_htlcs.contains(&first_payment_hash.0));
6717                 assert!(failed_htlcs.contains(&second_payment_hash.0));
6718                 assert!(failed_htlcs.contains(&third_payment_hash.0));
6719         }
6720
6721         #[test]
6722         fn test_commitment_revoked_fail_backward_exhaustive() {
6723                 do_test_commitment_revoked_fail_backward_exhaustive(false);
6724                 do_test_commitment_revoked_fail_backward_exhaustive(true);
6725         }
6726
6727         #[test]
6728         fn test_htlc_ignore_latest_remote_commitment() {
6729                 // Test that HTLC transactions spending the latest remote commitment transaction are simply
6730                 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
6731                 let nodes = create_network(2);
6732                 create_announced_chan_between_nodes(&nodes, 0, 1);
6733
6734                 route_payment(&nodes[0], &[&nodes[1]], 10000000);
6735                 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
6736                 {
6737                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6738                         assert_eq!(events.len(), 1);
6739                         match events[0] {
6740                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6741                                         assert_eq!(flags & 0b10, 0b10);
6742                                 },
6743                                 _ => panic!("Unexpected event"),
6744                         }
6745                 }
6746
6747                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6748                 assert_eq!(node_txn.len(), 2);
6749
6750                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6751                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6752
6753                 {
6754                         let events = nodes[1].node.get_and_clear_pending_msg_events();
6755                         assert_eq!(events.len(), 1);
6756                         match events[0] {
6757                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6758                                         assert_eq!(flags & 0b10, 0b10);
6759                                 },
6760                                 _ => panic!("Unexpected event"),
6761                         }
6762                 }
6763
6764                 // Duplicate the block_connected call since this may happen due to other listeners
6765                 // registering new transactions
6766                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6767         }
6768
6769         #[test]
6770         fn test_force_close_fail_back() {
6771                 // Check which HTLCs are failed-backwards on channel force-closure
6772                 let mut nodes = create_network(3);
6773                 create_announced_chan_between_nodes(&nodes, 0, 1);
6774                 create_announced_chan_between_nodes(&nodes, 1, 2);
6775
6776                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
6777
6778                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6779
6780                 let mut payment_event = {
6781                         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6782                         check_added_monitors!(nodes[0], 1);
6783
6784                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6785                         assert_eq!(events.len(), 1);
6786                         SendEvent::from_event(events.remove(0))
6787                 };
6788
6789                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6790                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6791
6792                 let events_1 = nodes[1].node.get_and_clear_pending_events();
6793                 assert_eq!(events_1.len(), 1);
6794                 match events_1[0] {
6795                         Event::PendingHTLCsForwardable { .. } => { },
6796                         _ => panic!("Unexpected event"),
6797                 };
6798
6799                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
6800                 nodes[1].node.process_pending_htlc_forwards();
6801
6802                 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6803                 assert_eq!(events_2.len(), 1);
6804                 payment_event = SendEvent::from_event(events_2.remove(0));
6805                 assert_eq!(payment_event.msgs.len(), 1);
6806
6807                 check_added_monitors!(nodes[1], 1);
6808                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6809                 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
6810                 check_added_monitors!(nodes[2], 1);
6811                 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6812
6813                 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
6814                 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
6815                 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
6816
6817                 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
6818                 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6819                 assert_eq!(events_3.len(), 1);
6820                 match events_3[0] {
6821                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6822                                 assert_eq!(flags & 0b10, 0b10);
6823                         },
6824                         _ => panic!("Unexpected event"),
6825                 }
6826
6827                 let tx = {
6828                         let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6829                         // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
6830                         // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
6831                         // back to nodes[1] upon timeout otherwise.
6832                         assert_eq!(node_txn.len(), 1);
6833                         node_txn.remove(0)
6834                 };
6835
6836                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6837                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6838
6839                 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6840                 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
6841                 assert_eq!(events_4.len(), 1);
6842                 match events_4[0] {
6843                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6844                                 assert_eq!(flags & 0b10, 0b10);
6845                         },
6846                         _ => panic!("Unexpected event"),
6847                 }
6848
6849                 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
6850                 {
6851                         let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
6852                         monitors.get_mut(&OutPoint::new(Sha256dHash::from(&payment_event.commitment_msg.channel_id[..]), 0)).unwrap()
6853                                 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
6854                 }
6855                 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6856                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6857                 assert_eq!(node_txn.len(), 1);
6858                 assert_eq!(node_txn[0].input.len(), 1);
6859                 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
6860                 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
6861                 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
6862
6863                 check_spends!(node_txn[0], tx);
6864         }
6865
6866         #[test]
6867         fn test_unconf_chan() {
6868                 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
6869                 let nodes = create_network(2);
6870                 create_announced_chan_between_nodes(&nodes, 0, 1);
6871
6872                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6873                 assert_eq!(channel_state.by_id.len(), 1);
6874                 assert_eq!(channel_state.short_to_id.len(), 1);
6875                 mem::drop(channel_state);
6876
6877                 let mut headers = Vec::new();
6878                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6879                 headers.push(header.clone());
6880                 for _i in 2..100 {
6881                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6882                         headers.push(header.clone());
6883                 }
6884                 while !headers.is_empty() {
6885                         nodes[0].node.block_disconnected(&headers.pop().unwrap());
6886                 }
6887                 {
6888                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6889                         assert_eq!(events.len(), 1);
6890                         match events[0] {
6891                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6892                                         assert_eq!(flags & 0b10, 0b10);
6893                                 },
6894                                 _ => panic!("Unexpected event"),
6895                         }
6896                 }
6897                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6898                 assert_eq!(channel_state.by_id.len(), 0);
6899                 assert_eq!(channel_state.short_to_id.len(), 0);
6900         }
6901
6902         macro_rules! get_chan_reestablish_msgs {
6903                 ($src_node: expr, $dst_node: expr) => {
6904                         {
6905                                 let mut res = Vec::with_capacity(1);
6906                                 for msg in $src_node.node.get_and_clear_pending_msg_events() {
6907                                         if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
6908                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6909                                                 res.push(msg.clone());
6910                                         } else {
6911                                                 panic!("Unexpected event")
6912                                         }
6913                                 }
6914                                 res
6915                         }
6916                 }
6917         }
6918
6919         macro_rules! handle_chan_reestablish_msgs {
6920                 ($src_node: expr, $dst_node: expr) => {
6921                         {
6922                                 let msg_events = $src_node.node.get_and_clear_pending_msg_events();
6923                                 let mut idx = 0;
6924                                 let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
6925                                         idx += 1;
6926                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6927                                         Some(msg.clone())
6928                                 } else {
6929                                         None
6930                                 };
6931
6932                                 let mut revoke_and_ack = None;
6933                                 let mut commitment_update = None;
6934                                 let order = if let Some(ev) = msg_events.get(idx) {
6935                                         idx += 1;
6936                                         match ev {
6937                                                 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6938                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6939                                                         revoke_and_ack = Some(msg.clone());
6940                                                         RAACommitmentOrder::RevokeAndACKFirst
6941                                                 },
6942                                                 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6943                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6944                                                         commitment_update = Some(updates.clone());
6945                                                         RAACommitmentOrder::CommitmentFirst
6946                                                 },
6947                                                 _ => panic!("Unexpected event"),
6948                                         }
6949                                 } else {
6950                                         RAACommitmentOrder::CommitmentFirst
6951                                 };
6952
6953                                 if let Some(ev) = msg_events.get(idx) {
6954                                         match ev {
6955                                                 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6956                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6957                                                         assert!(revoke_and_ack.is_none());
6958                                                         revoke_and_ack = Some(msg.clone());
6959                                                 },
6960                                                 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6961                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6962                                                         assert!(commitment_update.is_none());
6963                                                         commitment_update = Some(updates.clone());
6964                                                 },
6965                                                 _ => panic!("Unexpected event"),
6966                                         }
6967                                 }
6968
6969                                 (funding_locked, revoke_and_ack, commitment_update, order)
6970                         }
6971                 }
6972         }
6973
6974         /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
6975         /// for claims/fails they are separated out.
6976         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)) {
6977                 node_a.node.peer_connected(&node_b.node.get_our_node_id());
6978                 let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
6979                 node_b.node.peer_connected(&node_a.node.get_our_node_id());
6980                 let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
6981
6982                 if send_funding_locked.0 {
6983                         // If a expects a funding_locked, it better not think it has received a revoke_and_ack
6984                         // from b
6985                         for reestablish in reestablish_1.iter() {
6986                                 assert_eq!(reestablish.next_remote_commitment_number, 0);
6987                         }
6988                 }
6989                 if send_funding_locked.1 {
6990                         // If b expects a funding_locked, it better not think it has received a revoke_and_ack
6991                         // from a
6992                         for reestablish in reestablish_2.iter() {
6993                                 assert_eq!(reestablish.next_remote_commitment_number, 0);
6994                         }
6995                 }
6996                 if send_funding_locked.0 || send_funding_locked.1 {
6997                         // If we expect any funding_locked's, both sides better have set
6998                         // next_local_commitment_number to 1
6999                         for reestablish in reestablish_1.iter() {
7000                                 assert_eq!(reestablish.next_local_commitment_number, 1);
7001                         }
7002                         for reestablish in reestablish_2.iter() {
7003                                 assert_eq!(reestablish.next_local_commitment_number, 1);
7004                         }
7005                 }
7006
7007                 let mut resp_1 = Vec::new();
7008                 for msg in reestablish_1 {
7009                         node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg).unwrap();
7010                         resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
7011                 }
7012                 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
7013                         check_added_monitors!(node_b, 1);
7014                 } else {
7015                         check_added_monitors!(node_b, 0);
7016                 }
7017
7018                 let mut resp_2 = Vec::new();
7019                 for msg in reestablish_2 {
7020                         node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg).unwrap();
7021                         resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
7022                 }
7023                 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
7024                         check_added_monitors!(node_a, 1);
7025                 } else {
7026                         check_added_monitors!(node_a, 0);
7027                 }
7028
7029                 // We dont yet support both needing updates, as that would require a different commitment dance:
7030                 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
7031                         (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
7032
7033                 for chan_msgs in resp_1.drain(..) {
7034                         if send_funding_locked.0 {
7035                                 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
7036                                 let announcement_event = node_a.node.get_and_clear_pending_msg_events();
7037                                 if !announcement_event.is_empty() {
7038                                         assert_eq!(announcement_event.len(), 1);
7039                                         if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
7040                                                 //TODO: Test announcement_sigs re-sending
7041                                         } else { panic!("Unexpected event!"); }
7042                                 }
7043                         } else {
7044                                 assert!(chan_msgs.0.is_none());
7045                         }
7046                         if pending_raa.0 {
7047                                 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
7048                                 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
7049                                 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
7050                                 check_added_monitors!(node_a, 1);
7051                         } else {
7052                                 assert!(chan_msgs.1.is_none());
7053                         }
7054                         if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
7055                                 let commitment_update = chan_msgs.2.unwrap();
7056                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
7057                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
7058                                 } else {
7059                                         assert!(commitment_update.update_add_htlcs.is_empty());
7060                                 }
7061                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
7062                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
7063                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
7064                                 for update_add in commitment_update.update_add_htlcs {
7065                                         node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add).unwrap();
7066                                 }
7067                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
7068                                         node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill).unwrap();
7069                                 }
7070                                 for update_fail in commitment_update.update_fail_htlcs {
7071                                         node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail).unwrap();
7072                                 }
7073
7074                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
7075                                         commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
7076                                 } else {
7077                                         node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
7078                                         check_added_monitors!(node_a, 1);
7079                                         let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
7080                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
7081                                         node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7082                                         assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
7083                                         check_added_monitors!(node_b, 1);
7084                                 }
7085                         } else {
7086                                 assert!(chan_msgs.2.is_none());
7087                         }
7088                 }
7089
7090                 for chan_msgs in resp_2.drain(..) {
7091                         if send_funding_locked.1 {
7092                                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
7093                                 let announcement_event = node_b.node.get_and_clear_pending_msg_events();
7094                                 if !announcement_event.is_empty() {
7095                                         assert_eq!(announcement_event.len(), 1);
7096                                         if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
7097                                                 //TODO: Test announcement_sigs re-sending
7098                                         } else { panic!("Unexpected event!"); }
7099                                 }
7100                         } else {
7101                                 assert!(chan_msgs.0.is_none());
7102                         }
7103                         if pending_raa.1 {
7104                                 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
7105                                 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
7106                                 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
7107                                 check_added_monitors!(node_b, 1);
7108                         } else {
7109                                 assert!(chan_msgs.1.is_none());
7110                         }
7111                         if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
7112                                 let commitment_update = chan_msgs.2.unwrap();
7113                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
7114                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
7115                                 }
7116                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
7117                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
7118                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
7119                                 for update_add in commitment_update.update_add_htlcs {
7120                                         node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add).unwrap();
7121                                 }
7122                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
7123                                         node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill).unwrap();
7124                                 }
7125                                 for update_fail in commitment_update.update_fail_htlcs {
7126                                         node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail).unwrap();
7127                                 }
7128
7129                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
7130                                         commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
7131                                 } else {
7132                                         node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
7133                                         check_added_monitors!(node_b, 1);
7134                                         let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
7135                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
7136                                         node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7137                                         assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
7138                                         check_added_monitors!(node_a, 1);
7139                                 }
7140                         } else {
7141                                 assert!(chan_msgs.2.is_none());
7142                         }
7143                 }
7144         }
7145
7146         #[test]
7147         fn test_simple_peer_disconnect() {
7148                 // Test that we can reconnect when there are no lost messages
7149                 let nodes = create_network(3);
7150                 create_announced_chan_between_nodes(&nodes, 0, 1);
7151                 create_announced_chan_between_nodes(&nodes, 1, 2);
7152
7153                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7154                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7155                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7156
7157                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7158                 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7159                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
7160                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
7161
7162                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7163                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7164                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7165
7166                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7167                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7168                 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7169                 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7170
7171                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7172                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7173
7174                 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3);
7175                 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
7176
7177                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
7178                 {
7179                         let events = nodes[0].node.get_and_clear_pending_events();
7180                         assert_eq!(events.len(), 2);
7181                         match events[0] {
7182                                 Event::PaymentSent { payment_preimage } => {
7183                                         assert_eq!(payment_preimage, payment_preimage_3);
7184                                 },
7185                                 _ => panic!("Unexpected event"),
7186                         }
7187                         match events[1] {
7188                                 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
7189                                         assert_eq!(payment_hash, payment_hash_5);
7190                                         assert!(rejected_by_dest);
7191                                 },
7192                                 _ => panic!("Unexpected event"),
7193                         }
7194                 }
7195
7196                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
7197                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
7198         }
7199
7200         fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
7201                 // Test that we can reconnect when in-flight HTLC updates get dropped
7202                 let mut nodes = create_network(2);
7203                 if messages_delivered == 0 {
7204                         create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
7205                         // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
7206                 } else {
7207                         create_announced_chan_between_nodes(&nodes, 0, 1);
7208                 }
7209
7210                 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();
7211                 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7212
7213                 let payment_event = {
7214                         nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
7215                         check_added_monitors!(nodes[0], 1);
7216
7217                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7218                         assert_eq!(events.len(), 1);
7219                         SendEvent::from_event(events.remove(0))
7220                 };
7221                 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
7222
7223                 if messages_delivered < 2 {
7224                         // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
7225                 } else {
7226                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7227                         if messages_delivered >= 3 {
7228                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7229                                 check_added_monitors!(nodes[1], 1);
7230                                 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7231
7232                                 if messages_delivered >= 4 {
7233                                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7234                                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7235                                         check_added_monitors!(nodes[0], 1);
7236
7237                                         if messages_delivered >= 5 {
7238                                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
7239                                                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7240                                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7241                                                 check_added_monitors!(nodes[0], 1);
7242
7243                                                 if messages_delivered >= 6 {
7244                                                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7245                                                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7246                                                         check_added_monitors!(nodes[1], 1);
7247                                                 }
7248                                         }
7249                                 }
7250                         }
7251                 }
7252
7253                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7254                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7255                 if messages_delivered < 3 {
7256                         // Even if the funding_locked messages get exchanged, as long as nothing further was
7257                         // received on either side, both sides will need to resend them.
7258                         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
7259                 } else if messages_delivered == 3 {
7260                         // nodes[0] still wants its RAA + commitment_signed
7261                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
7262                 } else if messages_delivered == 4 {
7263                         // nodes[0] still wants its commitment_signed
7264                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
7265                 } else if messages_delivered == 5 {
7266                         // nodes[1] still wants its final RAA
7267                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
7268                 } else if messages_delivered == 6 {
7269                         // Everything was delivered...
7270                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7271                 }
7272
7273                 let events_1 = nodes[1].node.get_and_clear_pending_events();
7274                 assert_eq!(events_1.len(), 1);
7275                 match events_1[0] {
7276                         Event::PendingHTLCsForwardable { .. } => { },
7277                         _ => panic!("Unexpected event"),
7278                 };
7279
7280                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7281                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7282                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7283
7284                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7285                 nodes[1].node.process_pending_htlc_forwards();
7286
7287                 let events_2 = nodes[1].node.get_and_clear_pending_events();
7288                 assert_eq!(events_2.len(), 1);
7289                 match events_2[0] {
7290                         Event::PaymentReceived { ref payment_hash, amt } => {
7291                                 assert_eq!(payment_hash_1, *payment_hash);
7292                                 assert_eq!(amt, 1000000);
7293                         },
7294                         _ => panic!("Unexpected event"),
7295                 }
7296
7297                 nodes[1].node.claim_funds(payment_preimage_1);
7298                 check_added_monitors!(nodes[1], 1);
7299
7300                 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
7301                 assert_eq!(events_3.len(), 1);
7302                 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
7303                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
7304                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7305                                 assert!(updates.update_add_htlcs.is_empty());
7306                                 assert!(updates.update_fail_htlcs.is_empty());
7307                                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
7308                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
7309                                 assert!(updates.update_fee.is_none());
7310                                 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
7311                         },
7312                         _ => panic!("Unexpected event"),
7313                 };
7314
7315                 if messages_delivered >= 1 {
7316                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc).unwrap();
7317
7318                         let events_4 = nodes[0].node.get_and_clear_pending_events();
7319                         assert_eq!(events_4.len(), 1);
7320                         match events_4[0] {
7321                                 Event::PaymentSent { ref payment_preimage } => {
7322                                         assert_eq!(payment_preimage_1, *payment_preimage);
7323                                 },
7324                                 _ => panic!("Unexpected event"),
7325                         }
7326
7327                         if messages_delivered >= 2 {
7328                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
7329                                 check_added_monitors!(nodes[0], 1);
7330                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7331
7332                                 if messages_delivered >= 3 {
7333                                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7334                                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7335                                         check_added_monitors!(nodes[1], 1);
7336
7337                                         if messages_delivered >= 4 {
7338                                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
7339                                                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7340                                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7341                                                 check_added_monitors!(nodes[1], 1);
7342
7343                                                 if messages_delivered >= 5 {
7344                                                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7345                                                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7346                                                         check_added_monitors!(nodes[0], 1);
7347                                                 }
7348                                         }
7349                                 }
7350                         }
7351                 }
7352
7353                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7354                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7355                 if messages_delivered < 2 {
7356                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
7357                         //TODO: Deduplicate PaymentSent events, then enable this if:
7358                         //if messages_delivered < 1 {
7359                                 let events_4 = nodes[0].node.get_and_clear_pending_events();
7360                                 assert_eq!(events_4.len(), 1);
7361                                 match events_4[0] {
7362                                         Event::PaymentSent { ref payment_preimage } => {
7363                                                 assert_eq!(payment_preimage_1, *payment_preimage);
7364                                         },
7365                                         _ => panic!("Unexpected event"),
7366                                 }
7367                         //}
7368                 } else if messages_delivered == 2 {
7369                         // nodes[0] still wants its RAA + commitment_signed
7370                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
7371                 } else if messages_delivered == 3 {
7372                         // nodes[0] still wants its commitment_signed
7373                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
7374                 } else if messages_delivered == 4 {
7375                         // nodes[1] still wants its final RAA
7376                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
7377                 } else if messages_delivered == 5 {
7378                         // Everything was delivered...
7379                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7380                 }
7381
7382                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7383                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7384                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7385
7386                 // Channel should still work fine...
7387                 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
7388                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7389         }
7390
7391         #[test]
7392         fn test_drop_messages_peer_disconnect_a() {
7393                 do_test_drop_messages_peer_disconnect(0);
7394                 do_test_drop_messages_peer_disconnect(1);
7395                 do_test_drop_messages_peer_disconnect(2);
7396                 do_test_drop_messages_peer_disconnect(3);
7397         }
7398
7399         #[test]
7400         fn test_drop_messages_peer_disconnect_b() {
7401                 do_test_drop_messages_peer_disconnect(4);
7402                 do_test_drop_messages_peer_disconnect(5);
7403                 do_test_drop_messages_peer_disconnect(6);
7404         }
7405
7406         #[test]
7407         fn test_funding_peer_disconnect() {
7408                 // Test that we can lock in our funding tx while disconnected
7409                 let nodes = create_network(2);
7410                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
7411
7412                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7413                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7414
7415                 confirm_transaction(&nodes[0].chain_monitor, &tx, tx.version);
7416                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7417                 assert_eq!(events_1.len(), 1);
7418                 match events_1[0] {
7419                         MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7420                                 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7421                         },
7422                         _ => panic!("Unexpected event"),
7423                 }
7424
7425                 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7426
7427                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7428                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7429
7430                 confirm_transaction(&nodes[1].chain_monitor, &tx, tx.version);
7431                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7432                 assert_eq!(events_2.len(), 2);
7433                 match events_2[0] {
7434                         MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7435                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7436                         },
7437                         _ => panic!("Unexpected event"),
7438                 }
7439                 match events_2[1] {
7440                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ } => {
7441                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7442                         },
7443                         _ => panic!("Unexpected event"),
7444                 }
7445
7446                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7447
7448                 // TODO: We shouldn't need to manually pass list_usable_chanels here once we support
7449                 // rebroadcasting announcement_signatures upon reconnect.
7450
7451                 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();
7452                 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
7453                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
7454         }
7455
7456         #[test]
7457         fn test_drop_messages_peer_disconnect_dual_htlc() {
7458                 // Test that we can handle reconnecting when both sides of a channel have pending
7459                 // commitment_updates when we disconnect.
7460                 let mut nodes = create_network(2);
7461                 create_announced_chan_between_nodes(&nodes, 0, 1);
7462
7463                 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7464
7465                 // Now try to send a second payment which will fail to send
7466                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7467                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7468
7469                 nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
7470                 check_added_monitors!(nodes[0], 1);
7471
7472                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7473                 assert_eq!(events_1.len(), 1);
7474                 match events_1[0] {
7475                         MessageSendEvent::UpdateHTLCs { .. } => {},
7476                         _ => panic!("Unexpected event"),
7477                 }
7478
7479                 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7480                 check_added_monitors!(nodes[1], 1);
7481
7482                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7483                 assert_eq!(events_2.len(), 1);
7484                 match events_2[0] {
7485                         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 } } => {
7486                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7487                                 assert!(update_add_htlcs.is_empty());
7488                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7489                                 assert!(update_fail_htlcs.is_empty());
7490                                 assert!(update_fail_malformed_htlcs.is_empty());
7491                                 assert!(update_fee.is_none());
7492
7493                                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7494                                 let events_3 = nodes[0].node.get_and_clear_pending_events();
7495                                 assert_eq!(events_3.len(), 1);
7496                                 match events_3[0] {
7497                                         Event::PaymentSent { ref payment_preimage } => {
7498                                                 assert_eq!(*payment_preimage, payment_preimage_1);
7499                                         },
7500                                         _ => panic!("Unexpected event"),
7501                                 }
7502
7503                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
7504                                 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7505                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7506                                 check_added_monitors!(nodes[0], 1);
7507                         },
7508                         _ => panic!("Unexpected event"),
7509                 }
7510
7511                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7512                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7513
7514                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7515                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7516                 assert_eq!(reestablish_1.len(), 1);
7517                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7518                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7519                 assert_eq!(reestablish_2.len(), 1);
7520
7521                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7522                 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7523                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7524                 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7525
7526                 assert!(as_resp.0.is_none());
7527                 assert!(bs_resp.0.is_none());
7528
7529                 assert!(bs_resp.1.is_none());
7530                 assert!(bs_resp.2.is_none());
7531
7532                 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7533
7534                 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
7535                 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
7536                 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7537                 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7538                 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
7539                 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();
7540                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7541                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7542                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7543                 check_added_monitors!(nodes[1], 1);
7544
7545                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap();
7546                 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7547                 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
7548                 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
7549                 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
7550                 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
7551                 assert!(bs_second_commitment_signed.update_fee.is_none());
7552                 check_added_monitors!(nodes[1], 1);
7553
7554                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7555                 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7556                 assert!(as_commitment_signed.update_add_htlcs.is_empty());
7557                 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
7558                 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
7559                 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
7560                 assert!(as_commitment_signed.update_fee.is_none());
7561                 check_added_monitors!(nodes[0], 1);
7562
7563                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
7564                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7565                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7566                 check_added_monitors!(nodes[0], 1);
7567
7568                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
7569                 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7570                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7571                 check_added_monitors!(nodes[1], 1);
7572
7573                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7574                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7575                 check_added_monitors!(nodes[1], 1);
7576
7577                 let events_4 = nodes[1].node.get_and_clear_pending_events();
7578                 assert_eq!(events_4.len(), 1);
7579                 match events_4[0] {
7580                         Event::PendingHTLCsForwardable { .. } => { },
7581                         _ => panic!("Unexpected event"),
7582                 };
7583
7584                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7585                 nodes[1].node.process_pending_htlc_forwards();
7586
7587                 let events_5 = nodes[1].node.get_and_clear_pending_events();
7588                 assert_eq!(events_5.len(), 1);
7589                 match events_5[0] {
7590                         Event::PaymentReceived { ref payment_hash, amt: _ } => {
7591                                 assert_eq!(payment_hash_2, *payment_hash);
7592                         },
7593                         _ => panic!("Unexpected event"),
7594                 }
7595
7596                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
7597                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7598                 check_added_monitors!(nodes[0], 1);
7599
7600                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7601         }
7602
7603         #[test]
7604         fn test_simple_monitor_permanent_update_fail() {
7605                 // Test that we handle a simple permanent monitor update failure
7606                 let mut nodes = create_network(2);
7607                 create_announced_chan_between_nodes(&nodes, 0, 1);
7608
7609                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7610                 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7611
7612                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7613                 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route, payment_hash_1) {} else { panic!(); }
7614                 check_added_monitors!(nodes[0], 1);
7615
7616                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7617                 assert_eq!(events_1.len(), 2);
7618                 match events_1[0] {
7619                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7620                         _ => panic!("Unexpected event"),
7621                 };
7622                 match events_1[1] {
7623                         MessageSendEvent::HandleError { node_id, .. } => assert_eq!(node_id, nodes[1].node.get_our_node_id()),
7624                         _ => panic!("Unexpected event"),
7625                 };
7626
7627                 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7628                 // PaymentFailed event
7629
7630                 assert_eq!(nodes[0].node.list_channels().len(), 0);
7631         }
7632
7633         fn do_test_simple_monitor_temporary_update_fail(disconnect: bool) {
7634                 // Test that we can recover from a simple temporary monitor update failure optionally with
7635                 // a disconnect in between
7636                 let mut nodes = create_network(2);
7637                 create_announced_chan_between_nodes(&nodes, 0, 1);
7638
7639                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7640                 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7641
7642                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7643                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_1) {} else { panic!(); }
7644                 check_added_monitors!(nodes[0], 1);
7645
7646                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7647                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7648                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7649
7650                 if disconnect {
7651                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7652                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7653                         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7654                 }
7655
7656                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7657                 nodes[0].node.test_restore_channel_monitor();
7658                 check_added_monitors!(nodes[0], 1);
7659
7660                 let mut events_2 = nodes[0].node.get_and_clear_pending_msg_events();
7661                 assert_eq!(events_2.len(), 1);
7662                 let payment_event = SendEvent::from_event(events_2.pop().unwrap());
7663                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7664                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7665                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7666
7667                 expect_pending_htlcs_forwardable!(nodes[1]);
7668
7669                 let events_3 = nodes[1].node.get_and_clear_pending_events();
7670                 assert_eq!(events_3.len(), 1);
7671                 match events_3[0] {
7672                         Event::PaymentReceived { ref payment_hash, amt } => {
7673                                 assert_eq!(payment_hash_1, *payment_hash);
7674                                 assert_eq!(amt, 1000000);
7675                         },
7676                         _ => panic!("Unexpected event"),
7677                 }
7678
7679                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_1);
7680
7681                 // Now set it to failed again...
7682                 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7683                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7684                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route, payment_hash_2) {} else { panic!(); }
7685                 check_added_monitors!(nodes[0], 1);
7686
7687                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7688                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7689                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7690
7691                 if disconnect {
7692                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7693                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7694                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7695                 }
7696
7697                 // ...and make sure we can force-close a TemporaryFailure channel with a PermanentFailure
7698                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7699                 nodes[0].node.test_restore_channel_monitor();
7700                 check_added_monitors!(nodes[0], 1);
7701
7702                 let events_5 = nodes[0].node.get_and_clear_pending_msg_events();
7703                 assert_eq!(events_5.len(), 1);
7704                 match events_5[0] {
7705                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7706                         _ => panic!("Unexpected event"),
7707                 }
7708
7709                 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7710                 // PaymentFailed event
7711
7712                 assert_eq!(nodes[0].node.list_channels().len(), 0);
7713         }
7714
7715         #[test]
7716         fn test_simple_monitor_temporary_update_fail() {
7717                 do_test_simple_monitor_temporary_update_fail(false);
7718                 do_test_simple_monitor_temporary_update_fail(true);
7719         }
7720
7721         fn do_test_monitor_temporary_update_fail(disconnect_count: usize) {
7722                 let disconnect_flags = 8 | 16;
7723
7724                 // Test that we can recover from a temporary monitor update failure with some in-flight
7725                 // HTLCs going on at the same time potentially with some disconnection thrown in.
7726                 // * First we route a payment, then get a temporary monitor update failure when trying to
7727                 //   route a second payment. We then claim the first payment.
7728                 // * If disconnect_count is set, we will disconnect at this point (which is likely as
7729                 //   TemporaryFailure likely indicates net disconnect which resulted in failing to update
7730                 //   the ChannelMonitor on a watchtower).
7731                 // * If !(disconnect_count & 16) we deliver a update_fulfill_htlc/CS for the first payment
7732                 //   immediately, otherwise we wait sconnect and deliver them via the reconnect
7733                 //   channel_reestablish processing (ie disconnect_count & 16 makes no sense if
7734                 //   disconnect_count & !disconnect_flags is 0).
7735                 // * We then update the channel monitor, reconnecting if disconnect_count is set and walk
7736                 //   through message sending, potentially disconnect/reconnecting multiple times based on
7737                 //   disconnect_count, to get the update_fulfill_htlc through.
7738                 // * We then walk through more message exchanges to get the original update_add_htlc
7739                 //   through, swapping message ordering based on disconnect_count & 8 and optionally
7740                 //   disconnect/reconnecting based on disconnect_count.
7741                 let mut nodes = create_network(2);
7742                 create_announced_chan_between_nodes(&nodes, 0, 1);
7743
7744                 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7745
7746                 // Now try to send a second payment which will fail to send
7747                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7748                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7749
7750                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7751                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_2) {} else { panic!(); }
7752                 check_added_monitors!(nodes[0], 1);
7753
7754                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7755                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7756                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7757
7758                 // Claim the previous payment, which will result in a update_fulfill_htlc/CS from nodes[1]
7759                 // but nodes[0] won't respond since it is frozen.
7760                 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7761                 check_added_monitors!(nodes[1], 1);
7762                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7763                 assert_eq!(events_2.len(), 1);
7764                 let (bs_initial_fulfill, bs_initial_commitment_signed) = match events_2[0] {
7765                         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 } } => {
7766                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7767                                 assert!(update_add_htlcs.is_empty());
7768                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7769                                 assert!(update_fail_htlcs.is_empty());
7770                                 assert!(update_fail_malformed_htlcs.is_empty());
7771                                 assert!(update_fee.is_none());
7772
7773                                 if (disconnect_count & 16) == 0 {
7774                                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7775                                         let events_3 = nodes[0].node.get_and_clear_pending_events();
7776                                         assert_eq!(events_3.len(), 1);
7777                                         match events_3[0] {
7778                                                 Event::PaymentSent { ref payment_preimage } => {
7779                                                         assert_eq!(*payment_preimage, payment_preimage_1);
7780                                                 },
7781                                                 _ => panic!("Unexpected event"),
7782                                         }
7783
7784                                         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) {
7785                                                 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
7786                                         } else { panic!(); }
7787                                 }
7788
7789                                 (update_fulfill_htlcs[0].clone(), commitment_signed.clone())
7790                         },
7791                         _ => panic!("Unexpected event"),
7792                 };
7793
7794                 if disconnect_count & !disconnect_flags > 0 {
7795                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7796                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7797                 }
7798
7799                 // Now fix monitor updating...
7800                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7801                 nodes[0].node.test_restore_channel_monitor();
7802                 check_added_monitors!(nodes[0], 1);
7803
7804                 macro_rules! disconnect_reconnect_peers { () => { {
7805                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7806                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7807
7808                         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7809                         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7810                         assert_eq!(reestablish_1.len(), 1);
7811                         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7812                         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7813                         assert_eq!(reestablish_2.len(), 1);
7814
7815                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7816                         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7817                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7818                         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7819
7820                         assert!(as_resp.0.is_none());
7821                         assert!(bs_resp.0.is_none());
7822
7823                         (reestablish_1, reestablish_2, as_resp, bs_resp)
7824                 } } }
7825
7826                 let (payment_event, initial_revoke_and_ack) = if disconnect_count & !disconnect_flags > 0 {
7827                         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7828                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7829
7830                         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7831                         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7832                         assert_eq!(reestablish_1.len(), 1);
7833                         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7834                         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7835                         assert_eq!(reestablish_2.len(), 1);
7836
7837                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7838                         check_added_monitors!(nodes[0], 0);
7839                         let mut as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7840                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7841                         check_added_monitors!(nodes[1], 0);
7842                         let mut bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7843
7844                         assert!(as_resp.0.is_none());
7845                         assert!(bs_resp.0.is_none());
7846
7847                         assert!(bs_resp.1.is_none());
7848                         if (disconnect_count & 16) == 0 {
7849                                 assert!(bs_resp.2.is_none());
7850
7851                                 assert!(as_resp.1.is_some());
7852                                 assert!(as_resp.2.is_some());
7853                                 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7854                         } else {
7855                                 assert!(bs_resp.2.as_ref().unwrap().update_add_htlcs.is_empty());
7856                                 assert!(bs_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7857                                 assert!(bs_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7858                                 assert!(bs_resp.2.as_ref().unwrap().update_fee.is_none());
7859                                 assert!(bs_resp.2.as_ref().unwrap().update_fulfill_htlcs == vec![bs_initial_fulfill]);
7860                                 assert!(bs_resp.2.as_ref().unwrap().commitment_signed == bs_initial_commitment_signed);
7861
7862                                 assert!(as_resp.1.is_none());
7863
7864                                 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();
7865                                 let events_3 = nodes[0].node.get_and_clear_pending_events();
7866                                 assert_eq!(events_3.len(), 1);
7867                                 match events_3[0] {
7868                                         Event::PaymentSent { ref payment_preimage } => {
7869                                                 assert_eq!(*payment_preimage, payment_preimage_1);
7870                                         },
7871                                         _ => panic!("Unexpected event"),
7872                                 }
7873
7874                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7875                                 let as_resp_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7876                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7877                                 check_added_monitors!(nodes[0], 1);
7878
7879                                 as_resp.1 = Some(as_resp_raa);
7880                                 bs_resp.2 = None;
7881                         }
7882
7883                         if disconnect_count & !disconnect_flags > 1 {
7884                                 let (second_reestablish_1, second_reestablish_2, second_as_resp, second_bs_resp) = disconnect_reconnect_peers!();
7885
7886                                 if (disconnect_count & 16) == 0 {
7887                                         assert!(reestablish_1 == second_reestablish_1);
7888                                         assert!(reestablish_2 == second_reestablish_2);
7889                                 }
7890                                 assert!(as_resp == second_as_resp);
7891                                 assert!(bs_resp == second_bs_resp);
7892                         }
7893
7894                         (SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), as_resp.2.unwrap()), as_resp.1.unwrap())
7895                 } else {
7896                         let mut events_4 = nodes[0].node.get_and_clear_pending_msg_events();
7897                         assert_eq!(events_4.len(), 2);
7898                         (SendEvent::from_event(events_4.remove(0)), match events_4[0] {
7899                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
7900                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7901                                         msg.clone()
7902                                 },
7903                                 _ => panic!("Unexpected event"),
7904                         })
7905                 };
7906
7907                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7908
7909                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7910                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7911                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7912                 // nodes[1] is awaiting an RAA from nodes[0] still so get_event_msg's assert(len == 1) passes
7913                 check_added_monitors!(nodes[1], 1);
7914
7915                 if disconnect_count & !disconnect_flags > 2 {
7916                         let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7917
7918                         assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7919                         assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7920
7921                         assert!(as_resp.2.is_none());
7922                         assert!(bs_resp.2.is_none());
7923                 }
7924
7925                 let as_commitment_update;
7926                 let bs_second_commitment_update;
7927
7928                 macro_rules! handle_bs_raa { () => {
7929                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7930                         as_commitment_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7931                         assert!(as_commitment_update.update_add_htlcs.is_empty());
7932                         assert!(as_commitment_update.update_fulfill_htlcs.is_empty());
7933                         assert!(as_commitment_update.update_fail_htlcs.is_empty());
7934                         assert!(as_commitment_update.update_fail_malformed_htlcs.is_empty());
7935                         assert!(as_commitment_update.update_fee.is_none());
7936                         check_added_monitors!(nodes[0], 1);
7937                 } }
7938
7939                 macro_rules! handle_initial_raa { () => {
7940                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &initial_revoke_and_ack).unwrap();
7941                         bs_second_commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7942                         assert!(bs_second_commitment_update.update_add_htlcs.is_empty());
7943                         assert!(bs_second_commitment_update.update_fulfill_htlcs.is_empty());
7944                         assert!(bs_second_commitment_update.update_fail_htlcs.is_empty());
7945                         assert!(bs_second_commitment_update.update_fail_malformed_htlcs.is_empty());
7946                         assert!(bs_second_commitment_update.update_fee.is_none());
7947                         check_added_monitors!(nodes[1], 1);
7948                 } }
7949
7950                 if (disconnect_count & 8) == 0 {
7951                         handle_bs_raa!();
7952
7953                         if disconnect_count & !disconnect_flags > 3 {
7954                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7955
7956                                 assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7957                                 assert!(bs_resp.1.is_none());
7958
7959                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7960                                 assert!(bs_resp.2.is_none());
7961
7962                                 assert!(as_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7963                         }
7964
7965                         handle_initial_raa!();
7966
7967                         if disconnect_count & !disconnect_flags > 4 {
7968                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7969
7970                                 assert!(as_resp.1.is_none());
7971                                 assert!(bs_resp.1.is_none());
7972
7973                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7974                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7975                         }
7976                 } else {
7977                         handle_initial_raa!();
7978
7979                         if disconnect_count & !disconnect_flags > 3 {
7980                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7981
7982                                 assert!(as_resp.1.is_none());
7983                                 assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7984
7985                                 assert!(as_resp.2.is_none());
7986                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7987
7988                                 assert!(bs_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7989                         }
7990
7991                         handle_bs_raa!();
7992
7993                         if disconnect_count & !disconnect_flags > 4 {
7994                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7995
7996                                 assert!(as_resp.1.is_none());
7997                                 assert!(bs_resp.1.is_none());
7998
7999                                 assert!(as_resp.2.unwrap() == as_commitment_update);
8000                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
8001                         }
8002                 }
8003
8004                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_update.commitment_signed).unwrap();
8005                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8006                 // No commitment_signed so get_event_msg's assert(len == 1) passes
8007                 check_added_monitors!(nodes[0], 1);
8008
8009                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_update.commitment_signed).unwrap();
8010                 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
8011                 // No commitment_signed so get_event_msg's assert(len == 1) passes
8012                 check_added_monitors!(nodes[1], 1);
8013
8014                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
8015                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8016                 check_added_monitors!(nodes[1], 1);
8017
8018                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
8019                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8020                 check_added_monitors!(nodes[0], 1);
8021
8022                 expect_pending_htlcs_forwardable!(nodes[1]);
8023
8024                 let events_5 = nodes[1].node.get_and_clear_pending_events();
8025                 assert_eq!(events_5.len(), 1);
8026                 match events_5[0] {
8027                         Event::PaymentReceived { ref payment_hash, amt } => {
8028                                 assert_eq!(payment_hash_2, *payment_hash);
8029                                 assert_eq!(amt, 1000000);
8030                         },
8031                         _ => panic!("Unexpected event"),
8032                 }
8033
8034                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
8035         }
8036
8037         #[test]
8038         fn test_monitor_temporary_update_fail_a() {
8039                 do_test_monitor_temporary_update_fail(0);
8040                 do_test_monitor_temporary_update_fail(1);
8041                 do_test_monitor_temporary_update_fail(2);
8042                 do_test_monitor_temporary_update_fail(3);
8043                 do_test_monitor_temporary_update_fail(4);
8044                 do_test_monitor_temporary_update_fail(5);
8045         }
8046
8047         #[test]
8048         fn test_monitor_temporary_update_fail_b() {
8049                 do_test_monitor_temporary_update_fail(2 | 8);
8050                 do_test_monitor_temporary_update_fail(3 | 8);
8051                 do_test_monitor_temporary_update_fail(4 | 8);
8052                 do_test_monitor_temporary_update_fail(5 | 8);
8053         }
8054
8055         #[test]
8056         fn test_monitor_temporary_update_fail_c() {
8057                 do_test_monitor_temporary_update_fail(1 | 16);
8058                 do_test_monitor_temporary_update_fail(2 | 16);
8059                 do_test_monitor_temporary_update_fail(3 | 16);
8060                 do_test_monitor_temporary_update_fail(2 | 8 | 16);
8061                 do_test_monitor_temporary_update_fail(3 | 8 | 16);
8062         }
8063
8064         #[test]
8065         fn test_monitor_update_fail_cs() {
8066                 // Tests handling of a monitor update failure when processing an incoming commitment_signed
8067                 let mut nodes = create_network(2);
8068                 create_announced_chan_between_nodes(&nodes, 0, 1);
8069
8070                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8071                 let (payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
8072                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
8073                 check_added_monitors!(nodes[0], 1);
8074
8075                 let send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8076                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8077
8078                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8079                 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() {
8080                         assert_eq!(err, "Failed to update ChannelMonitor");
8081                 } else { panic!(); }
8082                 check_added_monitors!(nodes[1], 1);
8083                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8084
8085                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8086                 nodes[1].node.test_restore_channel_monitor();
8087                 check_added_monitors!(nodes[1], 1);
8088                 let responses = nodes[1].node.get_and_clear_pending_msg_events();
8089                 assert_eq!(responses.len(), 2);
8090
8091                 match responses[0] {
8092                         MessageSendEvent::SendRevokeAndACK { ref msg, ref node_id } => {
8093                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8094                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &msg).unwrap();
8095                                 check_added_monitors!(nodes[0], 1);
8096                         },
8097                         _ => panic!("Unexpected event"),
8098                 }
8099                 match responses[1] {
8100                         MessageSendEvent::UpdateHTLCs { ref updates, ref node_id } => {
8101                                 assert!(updates.update_add_htlcs.is_empty());
8102                                 assert!(updates.update_fulfill_htlcs.is_empty());
8103                                 assert!(updates.update_fail_htlcs.is_empty());
8104                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8105                                 assert!(updates.update_fee.is_none());
8106                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8107
8108                                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8109                                 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() {
8110                                         assert_eq!(err, "Failed to update ChannelMonitor");
8111                                 } else { panic!(); }
8112                                 check_added_monitors!(nodes[0], 1);
8113                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8114                         },
8115                         _ => panic!("Unexpected event"),
8116                 }
8117
8118                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
8119                 nodes[0].node.test_restore_channel_monitor();
8120                 check_added_monitors!(nodes[0], 1);
8121
8122                 let final_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8123                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &final_raa).unwrap();
8124                 check_added_monitors!(nodes[1], 1);
8125
8126                 let mut events = nodes[1].node.get_and_clear_pending_events();
8127                 assert_eq!(events.len(), 1);
8128                 match events[0] {
8129                         Event::PendingHTLCsForwardable { .. } => { },
8130                         _ => panic!("Unexpected event"),
8131                 };
8132                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8133                 nodes[1].node.process_pending_htlc_forwards();
8134
8135                 events = nodes[1].node.get_and_clear_pending_events();
8136                 assert_eq!(events.len(), 1);
8137                 match events[0] {
8138                         Event::PaymentReceived { payment_hash, amt } => {
8139                                 assert_eq!(payment_hash, our_payment_hash);
8140                                 assert_eq!(amt, 1000000);
8141                         },
8142                         _ => panic!("Unexpected event"),
8143                 };
8144
8145                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
8146         }
8147
8148         fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) {
8149                 // Tests handling of a monitor update failure when processing an incoming RAA
8150                 let mut nodes = create_network(3);
8151                 create_announced_chan_between_nodes(&nodes, 0, 1);
8152                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
8153
8154                 // Rebalance a bit so that we can send backwards from 2 to 1.
8155                 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 5000000);
8156
8157                 // Route a first payment that we'll fail backwards
8158                 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
8159
8160                 // Fail the payment backwards, failing the monitor update on nodes[1]'s receipt of the RAA
8161                 assert!(nodes[2].node.fail_htlc_backwards(&payment_hash_1, PaymentFailReason::PreimageUnknown));
8162                 check_added_monitors!(nodes[2], 1);
8163
8164                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8165                 assert!(updates.update_add_htlcs.is_empty());
8166                 assert!(updates.update_fulfill_htlcs.is_empty());
8167                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8168                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8169                 assert!(updates.update_fee.is_none());
8170                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
8171
8172                 let bs_revoke_and_ack = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
8173                 check_added_monitors!(nodes[0], 0);
8174
8175                 // While the second channel is AwaitingRAA, forward a second payment to get it into the
8176                 // holding cell.
8177                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
8178                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8179                 nodes[0].node.send_payment(route, payment_hash_2).unwrap();
8180                 check_added_monitors!(nodes[0], 1);
8181
8182                 let mut send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8183                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8184                 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false);
8185
8186                 let events_1 = nodes[1].node.get_and_clear_pending_events();
8187                 assert_eq!(events_1.len(), 1);
8188                 match events_1[0] {
8189                         Event::PendingHTLCsForwardable { .. } => { },
8190                         _ => panic!("Unexpected event"),
8191                 };
8192
8193                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8194                 nodes[1].node.process_pending_htlc_forwards();
8195                 check_added_monitors!(nodes[1], 0);
8196                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8197
8198                 // Now fail monitor updating.
8199                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8200                 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() {
8201                         assert_eq!(err, "Failed to update ChannelMonitor");
8202                 } else { panic!(); }
8203                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8204                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8205                 check_added_monitors!(nodes[1], 1);
8206
8207                 // Attempt to forward a third payment but fail due to the second channel being unavailable
8208                 // for forwarding.
8209
8210                 let (_, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
8211                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8212                 nodes[0].node.send_payment(route, payment_hash_3).unwrap();
8213                 check_added_monitors!(nodes[0], 1);
8214
8215                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(()); // We succeed in updating the monitor for the first channel
8216                 send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8217                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8218                 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
8219                 check_added_monitors!(nodes[1], 0);
8220
8221                 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8222                 assert_eq!(events_2.len(), 1);
8223                 match events_2.remove(0) {
8224                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
8225                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8226                                 assert!(updates.update_fulfill_htlcs.is_empty());
8227                                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8228                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8229                                 assert!(updates.update_add_htlcs.is_empty());
8230                                 assert!(updates.update_fee.is_none());
8231
8232                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
8233                                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
8234
8235                                 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
8236                                 assert_eq!(msg_events.len(), 1);
8237                                 match msg_events[0] {
8238                                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
8239                                                 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
8240                                                 assert_eq!(msg.contents.flags & 2, 2); // temp disabled
8241                                         },
8242                                         _ => panic!("Unexpected event"),
8243                                 }
8244
8245                                 let events = nodes[0].node.get_and_clear_pending_events();
8246                                 assert_eq!(events.len(), 1);
8247                                 if let Event::PaymentFailed { payment_hash, rejected_by_dest, .. } = events[0] {
8248                                         assert_eq!(payment_hash, payment_hash_3);
8249                                         assert!(!rejected_by_dest);
8250                                 } else { panic!("Unexpected event!"); }
8251                         },
8252                         _ => panic!("Unexpected event type!"),
8253                 };
8254
8255                 let (payment_preimage_4, payment_hash_4) = if test_ignore_second_cs {
8256                         // Try to route another payment backwards from 2 to make sure 1 holds off on responding
8257                         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[0]);
8258                         let route = nodes[2].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8259                         nodes[2].node.send_payment(route, payment_hash_4).unwrap();
8260                         check_added_monitors!(nodes[2], 1);
8261
8262                         send_event = SendEvent::from_event(nodes[2].node.get_and_clear_pending_msg_events().remove(0));
8263                         nodes[1].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8264                         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) {
8265                                 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
8266                         } else { panic!(); }
8267                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8268                         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8269                         (Some(payment_preimage_4), Some(payment_hash_4))
8270                 } else { (None, None) };
8271
8272                 // Restore monitor updating, ensuring we immediately get a fail-back update and a
8273                 // update_add update.
8274                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8275                 nodes[1].node.test_restore_channel_monitor();
8276                 check_added_monitors!(nodes[1], 2);
8277
8278                 let mut events_3 = nodes[1].node.get_and_clear_pending_msg_events();
8279                 if test_ignore_second_cs {
8280                         assert_eq!(events_3.len(), 3);
8281                 } else {
8282                         assert_eq!(events_3.len(), 2);
8283                 }
8284
8285                 // Note that the ordering of the events for different nodes is non-prescriptive, though the
8286                 // ordering of the two events that both go to nodes[2] have to stay in the same order.
8287                 let messages_a = match events_3.pop().unwrap() {
8288                         MessageSendEvent::UpdateHTLCs { node_id, mut updates } => {
8289                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8290                                 assert!(updates.update_fulfill_htlcs.is_empty());
8291                                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8292                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8293                                 assert!(updates.update_add_htlcs.is_empty());
8294                                 assert!(updates.update_fee.is_none());
8295                                 (updates.update_fail_htlcs.remove(0), updates.commitment_signed)
8296                         },
8297                         _ => panic!("Unexpected event type!"),
8298                 };
8299                 let raa = if test_ignore_second_cs {
8300                         match events_3.remove(1) {
8301                                 MessageSendEvent::SendRevokeAndACK { node_id, msg } => {
8302                                         assert_eq!(node_id, nodes[2].node.get_our_node_id());
8303                                         Some(msg.clone())
8304                                 },
8305                                 _ => panic!("Unexpected event"),
8306                         }
8307                 } else { None };
8308                 let send_event_b = SendEvent::from_event(events_3.remove(0));
8309                 assert_eq!(send_event_b.node_id, nodes[2].node.get_our_node_id());
8310
8311                 // Now deliver the new messages...
8312
8313                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &messages_a.0).unwrap();
8314                 commitment_signed_dance!(nodes[0], nodes[1], messages_a.1, false);
8315                 let events_4 = nodes[0].node.get_and_clear_pending_events();
8316                 assert_eq!(events_4.len(), 1);
8317                 if let Event::PaymentFailed { payment_hash, rejected_by_dest, .. } = events_4[0] {
8318                         assert_eq!(payment_hash, payment_hash_1);
8319                         assert!(rejected_by_dest);
8320                 } else { panic!("Unexpected event!"); }
8321
8322                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event_b.msgs[0]).unwrap();
8323                 if test_ignore_second_cs {
8324                         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event_b.commitment_msg).unwrap();
8325                         check_added_monitors!(nodes[2], 1);
8326                         let bs_revoke_and_ack = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8327                         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa.unwrap()).unwrap();
8328                         check_added_monitors!(nodes[2], 1);
8329                         let bs_cs = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8330                         assert!(bs_cs.update_add_htlcs.is_empty());
8331                         assert!(bs_cs.update_fail_htlcs.is_empty());
8332                         assert!(bs_cs.update_fail_malformed_htlcs.is_empty());
8333                         assert!(bs_cs.update_fulfill_htlcs.is_empty());
8334                         assert!(bs_cs.update_fee.is_none());
8335
8336                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
8337                         check_added_monitors!(nodes[1], 1);
8338                         let as_cs = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
8339                         assert!(as_cs.update_add_htlcs.is_empty());
8340                         assert!(as_cs.update_fail_htlcs.is_empty());
8341                         assert!(as_cs.update_fail_malformed_htlcs.is_empty());
8342                         assert!(as_cs.update_fulfill_htlcs.is_empty());
8343                         assert!(as_cs.update_fee.is_none());
8344
8345                         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_cs.commitment_signed).unwrap();
8346                         check_added_monitors!(nodes[1], 1);
8347                         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
8348
8349                         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_cs.commitment_signed).unwrap();
8350                         check_added_monitors!(nodes[2], 1);
8351                         let bs_second_raa = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8352
8353                         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
8354                         check_added_monitors!(nodes[2], 1);
8355                         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
8356
8357                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_second_raa).unwrap();
8358                         check_added_monitors!(nodes[1], 1);
8359                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8360                 } else {
8361                         commitment_signed_dance!(nodes[2], nodes[1], send_event_b.commitment_msg, false);
8362                 }
8363
8364                 let events_5 = nodes[2].node.get_and_clear_pending_events();
8365                 assert_eq!(events_5.len(), 1);
8366                 match events_5[0] {
8367                         Event::PendingHTLCsForwardable { .. } => { },
8368                         _ => panic!("Unexpected event"),
8369                 };
8370
8371                 nodes[2].node.channel_state.lock().unwrap().next_forward = Instant::now();
8372                 nodes[2].node.process_pending_htlc_forwards();
8373
8374                 let events_6 = nodes[2].node.get_and_clear_pending_events();
8375                 assert_eq!(events_6.len(), 1);
8376                 match events_6[0] {
8377                         Event::PaymentReceived { payment_hash, .. } => { assert_eq!(payment_hash, payment_hash_2); },
8378                         _ => panic!("Unexpected event"),
8379                 };
8380
8381                 if test_ignore_second_cs {
8382                         let events_7 = nodes[1].node.get_and_clear_pending_events();
8383                         assert_eq!(events_7.len(), 1);
8384                         match events_7[0] {
8385                                 Event::PendingHTLCsForwardable { .. } => { },
8386                                 _ => panic!("Unexpected event"),
8387                         };
8388
8389                         nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8390                         nodes[1].node.process_pending_htlc_forwards();
8391                         check_added_monitors!(nodes[1], 1);
8392
8393                         send_event = SendEvent::from_node(&nodes[1]);
8394                         assert_eq!(send_event.node_id, nodes[0].node.get_our_node_id());
8395                         assert_eq!(send_event.msgs.len(), 1);
8396                         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8397                         commitment_signed_dance!(nodes[0], nodes[1], send_event.commitment_msg, false);
8398
8399                         let events_8 = nodes[0].node.get_and_clear_pending_events();
8400                         assert_eq!(events_8.len(), 1);
8401                         match events_8[0] {
8402                                 Event::PendingHTLCsForwardable { .. } => { },
8403                                 _ => panic!("Unexpected event"),
8404                         };
8405
8406                         nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
8407                         nodes[0].node.process_pending_htlc_forwards();
8408
8409                         let events_9 = nodes[0].node.get_and_clear_pending_events();
8410                         assert_eq!(events_9.len(), 1);
8411                         match events_9[0] {
8412                                 Event::PaymentReceived { payment_hash, .. } => assert_eq!(payment_hash, payment_hash_4.unwrap()),
8413                                 _ => panic!("Unexpected event"),
8414                         };
8415                         claim_payment(&nodes[2], &[&nodes[1], &nodes[0]], payment_preimage_4.unwrap());
8416                 }
8417
8418                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
8419         }
8420
8421         #[test]
8422         fn test_monitor_update_fail_raa() {
8423                 do_test_monitor_update_fail_raa(false);
8424                 do_test_monitor_update_fail_raa(true);
8425         }
8426
8427         #[test]
8428         fn test_monitor_update_fail_reestablish() {
8429                 // Simple test for message retransmission after monitor update failure on
8430                 // channel_reestablish generating a monitor update (which comes from freeing holding cell
8431                 // HTLCs).
8432                 let mut nodes = create_network(3);
8433                 create_announced_chan_between_nodes(&nodes, 0, 1);
8434                 create_announced_chan_between_nodes(&nodes, 1, 2);
8435
8436                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
8437
8438                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8439                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8440
8441                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
8442                 check_added_monitors!(nodes[2], 1);
8443                 let mut updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8444                 assert!(updates.update_add_htlcs.is_empty());
8445                 assert!(updates.update_fail_htlcs.is_empty());
8446                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8447                 assert!(updates.update_fee.is_none());
8448                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8449                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8450                 check_added_monitors!(nodes[1], 1);
8451                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8452                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
8453
8454                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8455                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8456                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8457
8458                 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
8459                 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8460
8461                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
8462
8463                 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() {
8464                         assert_eq!(err, "Failed to update ChannelMonitor");
8465                 } else { panic!(); }
8466                 check_added_monitors!(nodes[1], 1);
8467
8468                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8469                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8470
8471                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8472                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8473
8474                 assert!(as_reestablish == get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()));
8475                 assert!(bs_reestablish == get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id()));
8476
8477                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
8478
8479                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish).unwrap();
8480                 check_added_monitors!(nodes[1], 0);
8481                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8482
8483                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8484                 nodes[1].node.test_restore_channel_monitor();
8485                 check_added_monitors!(nodes[1], 1);
8486
8487                 updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8488                 assert!(updates.update_add_htlcs.is_empty());
8489                 assert!(updates.update_fail_htlcs.is_empty());
8490                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8491                 assert!(updates.update_fee.is_none());
8492                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8493                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8494                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
8495
8496                 let events = nodes[0].node.get_and_clear_pending_events();
8497                 assert_eq!(events.len(), 1);
8498                 match events[0] {
8499                         Event::PaymentSent { payment_preimage, .. } => assert_eq!(payment_preimage, our_payment_preimage),
8500                         _ => panic!("Unexpected event"),
8501                 }
8502         }
8503
8504         #[test]
8505         fn test_invalid_channel_announcement() {
8506                 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
8507                 let secp_ctx = Secp256k1::new();
8508                 let nodes = create_network(2);
8509
8510                 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1]);
8511
8512                 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8513                 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
8514                 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
8515                 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
8516
8517                 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 } );
8518
8519                 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
8520                 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
8521
8522                 let as_network_key = nodes[0].node.get_our_node_id();
8523                 let bs_network_key = nodes[1].node.get_our_node_id();
8524
8525                 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
8526
8527                 let mut chan_announcement;
8528
8529                 macro_rules! dummy_unsigned_msg {
8530                         () => {
8531                                 msgs::UnsignedChannelAnnouncement {
8532                                         features: msgs::GlobalFeatures::new(),
8533                                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
8534                                         short_channel_id: as_chan.get_short_channel_id().unwrap(),
8535                                         node_id_1: if were_node_one { as_network_key } else { bs_network_key },
8536                                         node_id_2: if were_node_one { bs_network_key } else { as_network_key },
8537                                         bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
8538                                         bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
8539                                         excess_data: Vec::new(),
8540                                 };
8541                         }
8542                 }
8543
8544                 macro_rules! sign_msg {
8545                         ($unsigned_msg: expr) => {
8546                                 let msghash = Message::from_slice(&Sha256dHash::from_data(&$unsigned_msg.encode()[..])[..]).unwrap();
8547                                 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
8548                                 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
8549                                 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].node.our_network_key);
8550                                 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].node.our_network_key);
8551                                 chan_announcement = msgs::ChannelAnnouncement {
8552                                         node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
8553                                         node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
8554                                         bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
8555                                         bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
8556                                         contents: $unsigned_msg
8557                                 }
8558                         }
8559                 }
8560
8561                 let unsigned_msg = dummy_unsigned_msg!();
8562                 sign_msg!(unsigned_msg);
8563                 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
8564                 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 } );
8565
8566                 // Configured with Network::Testnet
8567                 let mut unsigned_msg = dummy_unsigned_msg!();
8568                 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
8569                 sign_msg!(unsigned_msg);
8570                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
8571
8572                 let mut unsigned_msg = dummy_unsigned_msg!();
8573                 unsigned_msg.chain_hash = Sha256dHash::from_data(&[1,2,3,4,5,6,7,8,9]);
8574                 sign_msg!(unsigned_msg);
8575                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
8576         }
8577
8578         struct VecWriter(Vec<u8>);
8579         impl Writer for VecWriter {
8580                 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
8581                         self.0.extend_from_slice(buf);
8582                         Ok(())
8583                 }
8584                 fn size_hint(&mut self, size: usize) {
8585                         self.0.reserve_exact(size);
8586                 }
8587         }
8588
8589         #[test]
8590         fn test_no_txn_manager_serialize_deserialize() {
8591                 let mut nodes = create_network(2);
8592
8593                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
8594
8595                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8596
8597                 let nodes_0_serialized = nodes[0].node.encode();
8598                 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8599                 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8600
8601                 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())));
8602                 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8603                 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8604                 assert!(chan_0_monitor_read.is_empty());
8605
8606                 let mut nodes_0_read = &nodes_0_serialized[..];
8607                 let config = UserConfig::new();
8608                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8609                 let (_, nodes_0_deserialized) = {
8610                         let mut channel_monitors = HashMap::new();
8611                         channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8612                         <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8613                                 default_config: config,
8614                                 keys_manager,
8615                                 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8616                                 monitor: nodes[0].chan_monitor.clone(),
8617                                 chain_monitor: nodes[0].chain_monitor.clone(),
8618                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8619                                 logger: Arc::new(test_utils::TestLogger::new()),
8620                                 channel_monitors: &channel_monitors,
8621                         }).unwrap()
8622                 };
8623                 assert!(nodes_0_read.is_empty());
8624
8625                 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8626                 nodes[0].node = Arc::new(nodes_0_deserialized);
8627                 let nodes_0_as_listener: Arc<ChainListener> = nodes[0].node.clone();
8628                 nodes[0].chain_monitor.register_listener(Arc::downgrade(&nodes_0_as_listener));
8629                 assert_eq!(nodes[0].node.list_channels().len(), 1);
8630                 check_added_monitors!(nodes[0], 1);
8631
8632                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8633                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
8634                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8635                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
8636
8637                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
8638                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8639                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
8640                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8641
8642                 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8643                 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8644                 for node in nodes.iter() {
8645                         assert!(node.router.handle_channel_announcement(&announcement).unwrap());
8646                         node.router.handle_channel_update(&as_update).unwrap();
8647                         node.router.handle_channel_update(&bs_update).unwrap();
8648                 }
8649
8650                 send_payment(&nodes[0], &[&nodes[1]], 1000000);
8651         }
8652
8653         #[test]
8654         fn test_simple_manager_serialize_deserialize() {
8655                 let mut nodes = create_network(2);
8656                 create_announced_chan_between_nodes(&nodes, 0, 1);
8657
8658                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8659                 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8660
8661                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8662
8663                 let nodes_0_serialized = nodes[0].node.encode();
8664                 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8665                 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8666
8667                 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())));
8668                 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8669                 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8670                 assert!(chan_0_monitor_read.is_empty());
8671
8672                 let mut nodes_0_read = &nodes_0_serialized[..];
8673                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8674                 let (_, nodes_0_deserialized) = {
8675                         let mut channel_monitors = HashMap::new();
8676                         channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8677                         <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8678                                 default_config: UserConfig::new(),
8679                                 keys_manager,
8680                                 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8681                                 monitor: nodes[0].chan_monitor.clone(),
8682                                 chain_monitor: nodes[0].chain_monitor.clone(),
8683                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8684                                 logger: Arc::new(test_utils::TestLogger::new()),
8685                                 channel_monitors: &channel_monitors,
8686                         }).unwrap()
8687                 };
8688                 assert!(nodes_0_read.is_empty());
8689
8690                 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8691                 nodes[0].node = Arc::new(nodes_0_deserialized);
8692                 check_added_monitors!(nodes[0], 1);
8693
8694                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8695
8696                 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
8697                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
8698         }
8699
8700         #[test]
8701         fn test_manager_serialize_deserialize_inconsistent_monitor() {
8702                 // Test deserializing a ChannelManager with a out-of-date ChannelMonitor
8703                 let mut nodes = create_network(4);
8704                 create_announced_chan_between_nodes(&nodes, 0, 1);
8705                 create_announced_chan_between_nodes(&nodes, 2, 0);
8706                 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3);
8707
8708                 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
8709
8710                 // Serialize the ChannelManager here, but the monitor we keep up-to-date
8711                 let nodes_0_serialized = nodes[0].node.encode();
8712
8713                 route_payment(&nodes[0], &[&nodes[3]], 1000000);
8714                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8715                 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8716                 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8717
8718                 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
8719                 // nodes[3])
8720                 let mut node_0_monitors_serialized = Vec::new();
8721                 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
8722                         let mut writer = VecWriter(Vec::new());
8723                         monitor.1.write_for_disk(&mut writer).unwrap();
8724                         node_0_monitors_serialized.push(writer.0);
8725                 }
8726
8727                 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())));
8728                 let mut node_0_monitors = Vec::new();
8729                 for serialized in node_0_monitors_serialized.iter() {
8730                         let mut read = &serialized[..];
8731                         let (_, monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
8732                         assert!(read.is_empty());
8733                         node_0_monitors.push(monitor);
8734                 }
8735
8736                 let mut nodes_0_read = &nodes_0_serialized[..];
8737                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8738                 let (_, nodes_0_deserialized) = <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8739                         default_config: UserConfig::new(),
8740                         keys_manager,
8741                         fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8742                         monitor: nodes[0].chan_monitor.clone(),
8743                         chain_monitor: nodes[0].chain_monitor.clone(),
8744                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8745                         logger: Arc::new(test_utils::TestLogger::new()),
8746                         channel_monitors: &node_0_monitors.iter().map(|monitor| { (monitor.get_funding_txo().unwrap(), monitor) }).collect(),
8747                 }).unwrap();
8748                 assert!(nodes_0_read.is_empty());
8749
8750                 { // Channel close should result in a commitment tx and an HTLC tx
8751                         let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8752                         assert_eq!(txn.len(), 2);
8753                         assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
8754                         assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
8755                 }
8756
8757                 for monitor in node_0_monitors.drain(..) {
8758                         assert!(nodes[0].chan_monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor).is_ok());
8759                         check_added_monitors!(nodes[0], 1);
8760                 }
8761                 nodes[0].node = Arc::new(nodes_0_deserialized);
8762
8763                 // nodes[1] and nodes[2] have no lost state with nodes[0]...
8764                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8765                 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8766                 //... and we can even still claim the payment!
8767                 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
8768
8769                 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id());
8770                 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8771                 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id());
8772                 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) {
8773                         assert_eq!(msg.channel_id, channel_id);
8774                 } else { panic!("Unexpected result"); }
8775         }
8776
8777         macro_rules! check_spendable_outputs {
8778                 ($node: expr, $der_idx: expr) => {
8779                         {
8780                                 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
8781                                 let mut txn = Vec::new();
8782                                 for event in events {
8783                                         match event {
8784                                                 Event::SpendableOutputs { ref outputs } => {
8785                                                         for outp in outputs {
8786                                                                 match *outp {
8787                                                                         SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
8788                                                                                 let input = TxIn {
8789                                                                                         previous_output: outpoint.clone(),
8790                                                                                         script_sig: Script::new(),
8791                                                                                         sequence: 0,
8792                                                                                         witness: Vec::new(),
8793                                                                                 };
8794                                                                                 let outp = TxOut {
8795                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8796                                                                                         value: output.value,
8797                                                                                 };
8798                                                                                 let mut spend_tx = Transaction {
8799                                                                                         version: 2,
8800                                                                                         lock_time: 0,
8801                                                                                         input: vec![input],
8802                                                                                         output: vec![outp],
8803                                                                                 };
8804                                                                                 let secp_ctx = Secp256k1::new();
8805                                                                                 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
8806                                                                                 let witness_script = Address::p2pkh(&remotepubkey, Network::Testnet).script_pubkey();
8807                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8808                                                                                 let remotesig = secp_ctx.sign(&sighash, key);
8809                                                                                 spend_tx.input[0].witness.push(remotesig.serialize_der(&secp_ctx).to_vec());
8810                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8811                                                                                 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
8812                                                                                 txn.push(spend_tx);
8813                                                                         },
8814                                                                         SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
8815                                                                                 let input = TxIn {
8816                                                                                         previous_output: outpoint.clone(),
8817                                                                                         script_sig: Script::new(),
8818                                                                                         sequence: *to_self_delay as u32,
8819                                                                                         witness: Vec::new(),
8820                                                                                 };
8821                                                                                 let outp = TxOut {
8822                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8823                                                                                         value: output.value,
8824                                                                                 };
8825                                                                                 let mut spend_tx = Transaction {
8826                                                                                         version: 2,
8827                                                                                         lock_time: 0,
8828                                                                                         input: vec![input],
8829                                                                                         output: vec![outp],
8830                                                                                 };
8831                                                                                 let secp_ctx = Secp256k1::new();
8832                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
8833                                                                                 let local_delaysig = secp_ctx.sign(&sighash, key);
8834                                                                                 spend_tx.input[0].witness.push(local_delaysig.serialize_der(&secp_ctx).to_vec());
8835                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8836                                                                                 spend_tx.input[0].witness.push(vec!(0));
8837                                                                                 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
8838                                                                                 txn.push(spend_tx);
8839                                                                         },
8840                                                                         SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
8841                                                                                 let secp_ctx = Secp256k1::new();
8842                                                                                 let input = TxIn {
8843                                                                                         previous_output: outpoint.clone(),
8844                                                                                         script_sig: Script::new(),
8845                                                                                         sequence: 0,
8846                                                                                         witness: Vec::new(),
8847                                                                                 };
8848                                                                                 let outp = TxOut {
8849                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8850                                                                                         value: output.value,
8851                                                                                 };
8852                                                                                 let mut spend_tx = Transaction {
8853                                                                                         version: 2,
8854                                                                                         lock_time: 0,
8855                                                                                         input: vec![input],
8856                                                                                         output: vec![outp.clone()],
8857                                                                                 };
8858                                                                                 let secret = {
8859                                                                                         match ExtendedPrivKey::new_master(&secp_ctx, Network::Testnet, &$node.node_seed) {
8860                                                                                                 Ok(master_key) => {
8861                                                                                                         match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx)) {
8862                                                                                                                 Ok(key) => key,
8863                                                                                                                 Err(_) => panic!("Your RNG is busted"),
8864                                                                                                         }
8865                                                                                                 }
8866                                                                                                 Err(_) => panic!("Your rng is busted"),
8867                                                                                         }
8868                                                                                 };
8869                                                                                 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
8870                                                                                 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
8871                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8872                                                                                 let sig = secp_ctx.sign(&sighash, &secret.secret_key);
8873                                                                                 spend_tx.input[0].witness.push(sig.serialize_der(&secp_ctx).to_vec());
8874                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8875                                                                                 spend_tx.input[0].witness.push(pubkey.serialize().to_vec());
8876                                                                                 txn.push(spend_tx);
8877                                                                         },
8878                                                                 }
8879                                                         }
8880                                                 },
8881                                                 _ => panic!("Unexpected event"),
8882                                         };
8883                                 }
8884                                 txn
8885                         }
8886                 }
8887         }
8888
8889         #[test]
8890         fn test_claim_sizeable_push_msat() {
8891                 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
8892                 let nodes = create_network(2);
8893
8894                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8895                 nodes[1].node.force_close_channel(&chan.2);
8896                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8897                 match events[0] {
8898                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8899                         _ => panic!("Unexpected event"),
8900                 }
8901                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8902                 assert_eq!(node_txn.len(), 1);
8903                 check_spends!(node_txn[0], chan.3.clone());
8904                 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
8905
8906                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8907                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8908                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8909                 assert_eq!(spend_txn.len(), 1);
8910                 check_spends!(spend_txn[0], node_txn[0].clone());
8911         }
8912
8913         #[test]
8914         fn test_claim_on_remote_sizeable_push_msat() {
8915                 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8916                 // to_remote output is encumbered by a P2WPKH
8917
8918                 let nodes = create_network(2);
8919
8920                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8921                 nodes[0].node.force_close_channel(&chan.2);
8922                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8923                 match events[0] {
8924                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8925                         _ => panic!("Unexpected event"),
8926                 }
8927                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8928                 assert_eq!(node_txn.len(), 1);
8929                 check_spends!(node_txn[0], chan.3.clone());
8930                 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
8931
8932                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8933                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8934                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8935                 match events[0] {
8936                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8937                         _ => panic!("Unexpected event"),
8938                 }
8939                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8940                 assert_eq!(spend_txn.len(), 2);
8941                 assert_eq!(spend_txn[0], spend_txn[1]);
8942                 check_spends!(spend_txn[0], node_txn[0].clone());
8943         }
8944
8945         #[test]
8946         fn test_claim_on_remote_revoked_sizeable_push_msat() {
8947                 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8948                 // to_remote output is encumbered by a P2WPKH
8949
8950                 let nodes = create_network(2);
8951
8952                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
8953                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8954                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
8955                 assert_eq!(revoked_local_txn[0].input.len(), 1);
8956                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8957
8958                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8959                 let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8960                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
8961                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8962                 match events[0] {
8963                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8964                         _ => panic!("Unexpected event"),
8965                 }
8966                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8967                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8968                 assert_eq!(spend_txn.len(), 4);
8969                 assert_eq!(spend_txn[0], spend_txn[2]); // to_remote output on revoked remote commitment_tx
8970                 check_spends!(spend_txn[0], revoked_local_txn[0].clone());
8971                 assert_eq!(spend_txn[1], spend_txn[3]); // to_local output on local commitment tx
8972                 check_spends!(spend_txn[1], node_txn[0].clone());
8973         }
8974
8975         #[test]
8976         fn test_static_spendable_outputs_preimage_tx() {
8977                 let nodes = create_network(2);
8978
8979                 // Create some initial channels
8980                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8981
8982                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8983
8984                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8985                 assert_eq!(commitment_tx[0].input.len(), 1);
8986                 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
8987
8988                 // Settle A's commitment tx on B's chain
8989                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8990                 assert!(nodes[1].node.claim_funds(payment_preimage));
8991                 check_added_monitors!(nodes[1], 1);
8992                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
8993                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8994                 match events[0] {
8995                         MessageSendEvent::UpdateHTLCs { .. } => {},
8996                         _ => panic!("Unexpected event"),
8997                 }
8998                 match events[1] {
8999                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9000                         _ => panic!("Unexepected event"),
9001                 }
9002
9003                 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
9004                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 1 (local commitment tx), ChannelMonitor: 2 (1 preimage tx) * 2 (block-rescan)
9005                 check_spends!(node_txn[0], commitment_tx[0].clone());
9006                 assert_eq!(node_txn[0], node_txn[2]);
9007                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9008                 check_spends!(node_txn[1], chan_1.3.clone());
9009
9010                 let spend_txn = check_spendable_outputs!(nodes[1], 1); // , 0, 0, 1, 1);
9011                 assert_eq!(spend_txn.len(), 2);
9012                 assert_eq!(spend_txn[0], spend_txn[1]);
9013                 check_spends!(spend_txn[0], node_txn[0].clone());
9014         }
9015
9016         #[test]
9017         fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
9018                 let nodes = create_network(2);
9019
9020                 // Create some initial channels
9021                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9022
9023                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9024                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
9025                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9026                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9027
9028                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9029
9030                 let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9031                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9032                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9033                 match events[0] {
9034                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9035                         _ => panic!("Unexpected event"),
9036                 }
9037                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9038                 assert_eq!(node_txn.len(), 3);
9039                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]);
9040                 assert_eq!(node_txn[0].input.len(), 2);
9041                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
9042
9043                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9044                 assert_eq!(spend_txn.len(), 2);
9045                 assert_eq!(spend_txn[0], spend_txn[1]);
9046                 check_spends!(spend_txn[0], node_txn[0].clone());
9047         }
9048
9049         #[test]
9050         fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
9051                 let nodes = create_network(2);
9052
9053                 // Create some initial channels
9054                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9055
9056                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9057                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9058                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9059                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9060
9061                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9062
9063                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9064                 // A will generate HTLC-Timeout from revoked commitment tx
9065                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9066                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9067                 match events[0] {
9068                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9069                         _ => panic!("Unexpected event"),
9070                 }
9071                 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9072                 assert_eq!(revoked_htlc_txn.len(), 3);
9073                 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
9074                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
9075                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9076                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
9077                 check_spends!(revoked_htlc_txn[1], chan_1.3.clone());
9078
9079                 // B will generate justice tx from A's revoked commitment/HTLC tx
9080                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
9081                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9082                 match events[0] {
9083                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9084                         _ => panic!("Unexpected event"),
9085                 }
9086
9087                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9088                 assert_eq!(node_txn.len(), 4);
9089                 assert_eq!(node_txn[3].input.len(), 1);
9090                 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
9091
9092                 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
9093                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9094                 assert_eq!(spend_txn.len(), 3);
9095                 assert_eq!(spend_txn[0], spend_txn[1]);
9096                 check_spends!(spend_txn[0], node_txn[0].clone());
9097                 check_spends!(spend_txn[2], node_txn[3].clone());
9098         }
9099
9100         #[test]
9101         fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
9102                 let nodes = create_network(2);
9103
9104                 // Create some initial channels
9105                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9106
9107                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9108                 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9109                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9110                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9111
9112                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9113
9114                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9115                 // B will generate HTLC-Success from revoked commitment tx
9116                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9117                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9118                 match events[0] {
9119                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9120                         _ => panic!("Unexpected event"),
9121                 }
9122                 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9123
9124                 assert_eq!(revoked_htlc_txn.len(), 3);
9125                 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
9126                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
9127                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9128                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
9129
9130                 // A will generate justice tx from B's revoked commitment/HTLC tx
9131                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
9132                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9133                 match events[0] {
9134                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9135                         _ => panic!("Unexpected event"),
9136                 }
9137
9138                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9139                 assert_eq!(node_txn.len(), 4);
9140                 assert_eq!(node_txn[3].input.len(), 1);
9141                 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
9142
9143                 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
9144                 let spend_txn = check_spendable_outputs!(nodes[0], 1);
9145                 assert_eq!(spend_txn.len(), 5);
9146                 assert_eq!(spend_txn[0], spend_txn[2]);
9147                 assert_eq!(spend_txn[1], spend_txn[3]);
9148                 check_spends!(spend_txn[0], revoked_local_txn[0].clone()); // spending to_remote output from revoked local tx
9149                 check_spends!(spend_txn[1], node_txn[2].clone()); // spending justice tx output from revoked local tx htlc received output
9150                 check_spends!(spend_txn[4], node_txn[3].clone()); // spending justice tx output on htlc success tx
9151         }
9152
9153         #[test]
9154         fn test_onchain_to_onchain_claim() {
9155                 // Test that in case of channel closure, we detect the state of output thanks to
9156                 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
9157                 // First, have C claim an HTLC against its own latest commitment transaction.
9158                 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
9159                 // channel.
9160                 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
9161                 // gets broadcast.
9162
9163                 let nodes = create_network(3);
9164
9165                 // Create some initial channels
9166                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9167                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
9168
9169                 // Rebalance the network a bit by relaying one payment through all the channels ...
9170                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
9171                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
9172
9173                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
9174                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9175                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
9176                 check_spends!(commitment_tx[0], chan_2.3.clone());
9177                 nodes[2].node.claim_funds(payment_preimage);
9178                 check_added_monitors!(nodes[2], 1);
9179                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9180                 assert!(updates.update_add_htlcs.is_empty());
9181                 assert!(updates.update_fail_htlcs.is_empty());
9182                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
9183                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9184
9185                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
9186                 let events = nodes[2].node.get_and_clear_pending_msg_events();
9187                 assert_eq!(events.len(), 1);
9188                 match events[0] {
9189                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9190                         _ => panic!("Unexpected event"),
9191                 }
9192
9193                 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
9194                 assert_eq!(c_txn.len(), 3);
9195                 assert_eq!(c_txn[0], c_txn[2]);
9196                 assert_eq!(commitment_tx[0], c_txn[1]);
9197                 check_spends!(c_txn[1], chan_2.3.clone());
9198                 check_spends!(c_txn[2], c_txn[1].clone());
9199                 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
9200                 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9201                 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
9202                 assert_eq!(c_txn[0].lock_time, 0); // Success tx
9203
9204                 // 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
9205                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
9206                 {
9207                         let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9208                         assert_eq!(b_txn.len(), 4);
9209                         assert_eq!(b_txn[0], b_txn[3]);
9210                         check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
9211                         check_spends!(b_txn[2], b_txn[1].clone()); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
9212                         assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9213                         assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
9214                         assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
9215                         check_spends!(b_txn[0], c_txn[1].clone()); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
9216                         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9217                         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
9218                         assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
9219                         b_txn.clear();
9220                 }
9221                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
9222                 check_added_monitors!(nodes[1], 1);
9223                 match msg_events[0] {
9224                         MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
9225                         _ => panic!("Unexpected event"),
9226                 }
9227                 match msg_events[1] {
9228                         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, .. } } => {
9229                                 assert!(update_add_htlcs.is_empty());
9230                                 assert!(update_fail_htlcs.is_empty());
9231                                 assert_eq!(update_fulfill_htlcs.len(), 1);
9232                                 assert!(update_fail_malformed_htlcs.is_empty());
9233                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
9234                         },
9235                         _ => panic!("Unexpected event"),
9236                 };
9237                 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
9238                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9239                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
9240                 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9241                 assert_eq!(b_txn.len(), 3);
9242                 check_spends!(b_txn[1], chan_1.3); // Local commitment tx, issued by ChannelManager
9243                 assert_eq!(b_txn[0], b_txn[2]); // HTLC-Success tx, issued by ChannelMonitor, * 2 due to block rescan
9244                 check_spends!(b_txn[0], commitment_tx[0].clone());
9245                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9246                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
9247                 assert_eq!(b_txn[2].lock_time, 0); // Success tx
9248                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
9249                 match msg_events[0] {
9250                         MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
9251                         _ => panic!("Unexpected event"),
9252                 }
9253         }
9254
9255         #[test]
9256         fn test_duplicate_payment_hash_one_failure_one_success() {
9257                 // Topology : A --> B --> C
9258                 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
9259                 let mut nodes = create_network(3);
9260
9261                 create_announced_chan_between_nodes(&nodes, 0, 1);
9262                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
9263
9264                 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
9265                 *nodes[0].network_payment_count.borrow_mut() -= 1;
9266                 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
9267
9268                 let commitment_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
9269                 assert_eq!(commitment_txn[0].input.len(), 1);
9270                 check_spends!(commitment_txn[0], chan_2.3.clone());
9271
9272                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9273                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
9274                 let htlc_timeout_tx;
9275                 { // Extract one of the two HTLC-Timeout transaction
9276                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9277                         assert_eq!(node_txn.len(), 7);
9278                         assert_eq!(node_txn[0], node_txn[5]);
9279                         assert_eq!(node_txn[1], node_txn[6]);
9280                         check_spends!(node_txn[0], commitment_txn[0].clone());
9281                         assert_eq!(node_txn[0].input.len(), 1);
9282                         check_spends!(node_txn[1], commitment_txn[0].clone());
9283                         assert_eq!(node_txn[1].input.len(), 1);
9284                         assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
9285                         check_spends!(node_txn[2], chan_2.3.clone());
9286                         check_spends!(node_txn[3], node_txn[2].clone());
9287                         check_spends!(node_txn[4], node_txn[2].clone());
9288                         htlc_timeout_tx = node_txn[1].clone();
9289                 }
9290
9291                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9292                 match events[0] {
9293                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9294                         _ => panic!("Unexepected event"),
9295                 }
9296
9297                 nodes[2].node.claim_funds(our_payment_preimage);
9298                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
9299                 check_added_monitors!(nodes[2], 2);
9300                 let events = nodes[2].node.get_and_clear_pending_msg_events();
9301                 match events[0] {
9302                         MessageSendEvent::UpdateHTLCs { .. } => {},
9303                         _ => panic!("Unexpected event"),
9304                 }
9305                 match events[1] {
9306                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9307                         _ => panic!("Unexepected event"),
9308                 }
9309                 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9310                 assert_eq!(htlc_success_txn.len(), 5);
9311                 check_spends!(htlc_success_txn[2], chan_2.3.clone());
9312                 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
9313                 assert_eq!(htlc_success_txn[0].input.len(), 1);
9314                 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9315                 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
9316                 assert_eq!(htlc_success_txn[1].input.len(), 1);
9317                 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9318                 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
9319                 check_spends!(htlc_success_txn[0], commitment_txn[0].clone());
9320                 check_spends!(htlc_success_txn[1], commitment_txn[0].clone());
9321
9322                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
9323                 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9324                 assert!(htlc_updates.update_add_htlcs.is_empty());
9325                 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
9326                 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
9327                 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
9328                 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
9329                 check_added_monitors!(nodes[1], 1);
9330
9331                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]).unwrap();
9332                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9333                 {
9334                         commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
9335                         let events = nodes[0].node.get_and_clear_pending_msg_events();
9336                         assert_eq!(events.len(), 1);
9337                         match events[0] {
9338                                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
9339                                 },
9340                                 _ => { panic!("Unexpected event"); }
9341                         }
9342                 }
9343                 let events = nodes[0].node.get_and_clear_pending_events();
9344                 match events[0] {
9345                         Event::PaymentFailed { ref payment_hash, .. } => {
9346                                 assert_eq!(*payment_hash, duplicate_payment_hash);
9347                         }
9348                         _ => panic!("Unexpected event"),
9349                 }
9350
9351                 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
9352                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
9353                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9354                 assert!(updates.update_add_htlcs.is_empty());
9355                 assert!(updates.update_fail_htlcs.is_empty());
9356                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
9357                 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
9358                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9359                 check_added_monitors!(nodes[1], 1);
9360
9361                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
9362                 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
9363
9364                 let events = nodes[0].node.get_and_clear_pending_events();
9365                 match events[0] {
9366                         Event::PaymentSent { ref payment_preimage } => {
9367                                 assert_eq!(*payment_preimage, our_payment_preimage);
9368                         }
9369                         _ => panic!("Unexpected event"),
9370                 }
9371         }
9372
9373         #[test]
9374         fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
9375                 let nodes = create_network(2);
9376
9377                 // Create some initial channels
9378                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9379
9380                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
9381                 let local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9382                 assert_eq!(local_txn[0].input.len(), 1);
9383                 check_spends!(local_txn[0], chan_1.3.clone());
9384
9385                 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
9386                 nodes[1].node.claim_funds(payment_preimage);
9387                 check_added_monitors!(nodes[1], 1);
9388                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9389                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
9390                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9391                 match events[0] {
9392                         MessageSendEvent::UpdateHTLCs { .. } => {},
9393                         _ => panic!("Unexpected event"),
9394                 }
9395                 match events[1] {
9396                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9397                         _ => panic!("Unexepected event"),
9398                 }
9399                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9400                 assert_eq!(node_txn[0].input.len(), 1);
9401                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9402                 check_spends!(node_txn[0], local_txn[0].clone());
9403
9404                 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
9405                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9406                 assert_eq!(spend_txn.len(), 2);
9407                 check_spends!(spend_txn[0], node_txn[0].clone());
9408                 check_spends!(spend_txn[1], node_txn[2].clone());
9409         }
9410
9411         #[test]
9412         fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
9413                 let nodes = create_network(2);
9414
9415                 // Create some initial channels
9416                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9417
9418                 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
9419                 let local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9420                 assert_eq!(local_txn[0].input.len(), 1);
9421                 check_spends!(local_txn[0], chan_1.3.clone());
9422
9423                 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
9424                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9425                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
9426                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9427                 match events[0] {
9428                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9429                         _ => panic!("Unexepected event"),
9430                 }
9431                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9432                 assert_eq!(node_txn[0].input.len(), 1);
9433                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9434                 check_spends!(node_txn[0], local_txn[0].clone());
9435
9436                 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
9437                 let spend_txn = check_spendable_outputs!(nodes[0], 1);
9438                 assert_eq!(spend_txn.len(), 8);
9439                 assert_eq!(spend_txn[0], spend_txn[2]);
9440                 assert_eq!(spend_txn[0], spend_txn[4]);
9441                 assert_eq!(spend_txn[0], spend_txn[6]);
9442                 assert_eq!(spend_txn[1], spend_txn[3]);
9443                 assert_eq!(spend_txn[1], spend_txn[5]);
9444                 assert_eq!(spend_txn[1], spend_txn[7]);
9445                 check_spends!(spend_txn[0], local_txn[0].clone());
9446                 check_spends!(spend_txn[1], node_txn[0].clone());
9447         }
9448
9449         #[test]
9450         fn test_static_output_closing_tx() {
9451                 let nodes = create_network(2);
9452
9453                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
9454
9455                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
9456                 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
9457
9458                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9459                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
9460                 let spend_txn = check_spendable_outputs!(nodes[0], 2);
9461                 assert_eq!(spend_txn.len(), 1);
9462                 check_spends!(spend_txn[0], closing_tx.clone());
9463
9464                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
9465                 let spend_txn = check_spendable_outputs!(nodes[1], 2);
9466                 assert_eq!(spend_txn.len(), 1);
9467                 check_spends!(spend_txn[0], closing_tx);
9468         }
9469 }