Steal rust-crypto's ChaCha20 implementation wholesale
[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 bitcoin_hashes::{Hash, HashEngine};
18 use bitcoin_hashes::hmac::{Hmac, HmacEngine};
19 use bitcoin_hashes::sha256::Hash as Sha256;
20
21 use secp256k1::key::{SecretKey,PublicKey};
22 use secp256k1::{Secp256k1,Message};
23 use secp256k1::ecdh::SharedSecret;
24 use secp256k1;
25
26 use chain::chaininterface::{BroadcasterInterface,ChainListener,ChainWatchInterface,FeeEstimator};
27 use chain::transaction::OutPoint;
28 use ln::channel::{Channel, ChannelError};
29 use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, ManyChannelMonitor, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, HTLC_FAIL_ANTI_REORG_DELAY};
30 use ln::router::{Route,RouteHop};
31 use ln::msgs;
32 use ln::msgs::{ChannelMessageHandler, DecodeError, HandleError};
33 use chain::keysinterface::KeysInterface;
34 use util::config::UserConfig;
35 use util::{byte_utils, events, internal_traits, rng};
36 use util::ser::{Readable, ReadableArgs, Writeable, Writer};
37 use util::chacha20::ChaCha20;
38 use util::logger::Logger;
39 use util::errors::APIError;
40 use util::errors;
41
42 use crypto;
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 /// We hold back HTLCs we intend to relay for a random interval in the range (this, 5*this). This
216 /// provides some limited amount of privacy. Ideally this would range from somewhere like 1 second
217 /// to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly. We could
218 /// probably increase this significantly.
219 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
220
221 struct HTLCForwardInfo {
222         prev_short_channel_id: u64,
223         prev_htlc_id: u64,
224         forward_info: PendingForwardHTLCInfo,
225 }
226
227 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
228 /// be sent in the order they appear in the return value, however sometimes the order needs to be
229 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
230 /// they were originally sent). In those cases, this enum is also returned.
231 #[derive(Clone, PartialEq)]
232 pub(super) enum RAACommitmentOrder {
233         /// Send the CommitmentUpdate messages first
234         CommitmentFirst,
235         /// Send the RevokeAndACK message first
236         RevokeAndACKFirst,
237 }
238
239 struct ChannelHolder {
240         by_id: HashMap<[u8; 32], Channel>,
241         short_to_id: HashMap<u64, [u8; 32]>,
242         next_forward: Instant,
243         /// short channel id -> forward infos. Key of 0 means payments received
244         /// Note that while this is held in the same mutex as the channels themselves, no consistency
245         /// guarantees are made about there existing a channel with the short id here, nor the short
246         /// ids in the PendingForwardHTLCInfo!
247         forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
248         /// Note that while this is held in the same mutex as the channels themselves, no consistency
249         /// guarantees are made about the channels given here actually existing anymore by the time you
250         /// go to read them!
251         claimable_htlcs: HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
252         /// Messages to send to peers - pushed to in the same lock that they are generated in (except
253         /// for broadcast messages, where ordering isn't as strict).
254         pending_msg_events: Vec<events::MessageSendEvent>,
255 }
256 struct MutChannelHolder<'a> {
257         by_id: &'a mut HashMap<[u8; 32], Channel>,
258         short_to_id: &'a mut HashMap<u64, [u8; 32]>,
259         next_forward: &'a mut Instant,
260         forward_htlcs: &'a mut HashMap<u64, Vec<HTLCForwardInfo>>,
261         claimable_htlcs: &'a mut HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
262         pending_msg_events: &'a mut Vec<events::MessageSendEvent>,
263 }
264 impl ChannelHolder {
265         fn borrow_parts(&mut self) -> MutChannelHolder {
266                 MutChannelHolder {
267                         by_id: &mut self.by_id,
268                         short_to_id: &mut self.short_to_id,
269                         next_forward: &mut self.next_forward,
270                         forward_htlcs: &mut self.forward_htlcs,
271                         claimable_htlcs: &mut self.claimable_htlcs,
272                         pending_msg_events: &mut self.pending_msg_events,
273                 }
274         }
275 }
276
277 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
278 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
279
280 /// Manager which keeps track of a number of channels and sends messages to the appropriate
281 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
282 ///
283 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
284 /// to individual Channels.
285 ///
286 /// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
287 /// all peers during write/read (though does not modify this instance, only the instance being
288 /// serialized). This will result in any channels which have not yet exchanged funding_created (ie
289 /// called funding_transaction_generated for outbound channels).
290 ///
291 /// Note that you can be a bit lazier about writing out ChannelManager than you can be with
292 /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
293 /// returning from ManyChannelMonitor::add_update_monitor, with ChannelManagers, writing updates
294 /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during
295 /// the serialization process). If the deserialized version is out-of-date compared to the
296 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
297 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
298 ///
299 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelManager), which
300 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
301 /// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
302 /// block_connected() to step towards your best block) upon deserialization before using the
303 /// object!
304 pub struct ChannelManager {
305         default_configuration: UserConfig,
306         genesis_hash: Sha256dHash,
307         fee_estimator: Arc<FeeEstimator>,
308         monitor: Arc<ManyChannelMonitor>,
309         chain_monitor: Arc<ChainWatchInterface>,
310         tx_broadcaster: Arc<BroadcasterInterface>,
311
312         latest_block_height: AtomicUsize,
313         last_block_hash: Mutex<Sha256dHash>,
314         secp_ctx: Secp256k1<secp256k1::All>,
315
316         channel_state: Mutex<ChannelHolder>,
317         our_network_key: SecretKey,
318
319         pending_events: Mutex<Vec<events::Event>>,
320         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
321         /// Essentially just when we're serializing ourselves out.
322         /// Taken first everywhere where we are making changes before any other locks.
323         total_consistency_lock: RwLock<()>,
324
325         keys_manager: Arc<KeysInterface>,
326
327         logger: Arc<Logger>,
328 }
329
330 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
331 /// HTLC's CLTV. This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
332 /// ie the node we forwarded the payment on to should always have enough room to reliably time out
333 /// the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
334 /// CLTV_CLAIM_BUFFER point (we static assert that its at least 3 blocks more).
335 const CLTV_EXPIRY_DELTA: u16 = 6 * 12; //TODO?
336 const CLTV_FAR_FAR_AWAY: u32 = 6 * 24 * 7; //TODO?
337
338 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + 2*HTLC_FAIL_TIMEOUT_BLOCKS +
339 // HTLC_FAIL_ANTI_REORG_DELAY, ie that if the next-hop peer fails the HTLC within
340 // HTLC_FAIL_TIMEOUT_BLOCKS then we'll still have HTLC_FAIL_TIMEOUT_BLOCKS left to fail it
341 // backwards ourselves before hitting the CLTV_CLAIM_BUFFER point and failing the channel
342 // on-chain to time out the HTLC.
343 #[deny(const_err)]
344 #[allow(dead_code)]
345 const CHECK_CLTV_EXPIRY_SANITY: u32 = CLTV_EXPIRY_DELTA as u32 - 2*HTLC_FAIL_TIMEOUT_BLOCKS - CLTV_CLAIM_BUFFER - HTLC_FAIL_ANTI_REORG_DELAY;
346
347 // Check for ability of an attacker to make us fail on-chain by delaying inbound claim. See
348 // ChannelMontior::would_broadcast_at_height for a description of why this is needed.
349 #[deny(const_err)]
350 #[allow(dead_code)]
351 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = CLTV_EXPIRY_DELTA as u32 - HTLC_FAIL_TIMEOUT_BLOCKS - 2*CLTV_CLAIM_BUFFER;
352
353 macro_rules! secp_call {
354         ( $res: expr, $err: expr ) => {
355                 match $res {
356                         Ok(key) => key,
357                         Err(_) => return Err($err),
358                 }
359         };
360 }
361
362 struct OnionKeys {
363         #[cfg(test)]
364         shared_secret: SharedSecret,
365         #[cfg(test)]
366         blinding_factor: [u8; 32],
367         ephemeral_pubkey: PublicKey,
368         rho: [u8; 32],
369         mu: [u8; 32],
370 }
371
372 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
373 pub struct ChannelDetails {
374         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
375         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
376         /// Note that this means this value is *not* persistent - it can change once during the
377         /// lifetime of the channel.
378         pub channel_id: [u8; 32],
379         /// The position of the funding transaction in the chain. None if the funding transaction has
380         /// not yet been confirmed and the channel fully opened.
381         pub short_channel_id: Option<u64>,
382         /// The node_id of our counterparty
383         pub remote_network_id: PublicKey,
384         /// The value, in satoshis, of this channel as appears in the funding output
385         pub channel_value_satoshis: u64,
386         /// The user_id passed in to create_channel, or 0 if the channel was inbound.
387         pub user_id: u64,
388 }
389
390 macro_rules! handle_error {
391         ($self: ident, $internal: expr, $their_node_id: expr) => {
392                 match $internal {
393                         Ok(msg) => Ok(msg),
394                         Err(MsgHandleErrInternal { err, shutdown_finish }) => {
395                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
396                                         $self.finish_force_close_channel(shutdown_res);
397                                         if let Some(update) = update_option {
398                                                 let mut channel_state = $self.channel_state.lock().unwrap();
399                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
400                                                         msg: update
401                                                 });
402                                         }
403                                 }
404                                 Err(err)
405                         },
406                 }
407         }
408 }
409
410 macro_rules! break_chan_entry {
411         ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
412                 match $res {
413                         Ok(res) => res,
414                         Err(ChannelError::Ignore(msg)) => {
415                                 break Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
416                         },
417                         Err(ChannelError::Close(msg)) => {
418                                 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
419                                 let (channel_id, mut chan) = $entry.remove_entry();
420                                 if let Some(short_id) = chan.get_short_channel_id() {
421                                         $channel_state.short_to_id.remove(&short_id);
422                                 }
423                                 break Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
424                         },
425                 }
426         }
427 }
428
429 macro_rules! try_chan_entry {
430         ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
431                 match $res {
432                         Ok(res) => res,
433                         Err(ChannelError::Ignore(msg)) => {
434                                 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
435                         },
436                         Err(ChannelError::Close(msg)) => {
437                                 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
438                                 let (channel_id, mut chan) = $entry.remove_entry();
439                                 if let Some(short_id) = chan.get_short_channel_id() {
440                                         $channel_state.short_to_id.remove(&short_id);
441                                 }
442                                 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
443                         },
444                 }
445         }
446 }
447
448 macro_rules! return_monitor_err {
449         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
450                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new())
451         };
452         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $raa_first_dropped_cs: expr) => {
453                 if $action_type != RAACommitmentOrder::RevokeAndACKFirst { panic!("Bad return_monitor_err call!"); }
454                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new(), $raa_first_dropped_cs)
455         };
456         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr) => {
457                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, $failed_forwards, $failed_fails, false)
458         };
459         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr, $raa_first_dropped_cs: expr) => {
460                 match $err {
461                         ChannelMonitorUpdateErr::PermanentFailure => {
462                                 let (channel_id, mut chan) = $entry.remove_entry();
463                                 if let Some(short_id) = chan.get_short_channel_id() {
464                                         $channel_state.short_to_id.remove(&short_id);
465                                 }
466                                 // TODO: $failed_fails is dropped here, which will cause other channels to hit the
467                                 // chain in a confused state! We need to move them into the ChannelMonitor which
468                                 // will be responsible for failing backwards once things confirm on-chain.
469                                 // It's ok that we drop $failed_forwards here - at this point we'd rather they
470                                 // broadcast HTLC-Timeout and pay the associated fees to get their funds back than
471                                 // us bother trying to claim it just to forward on to another peer. If we're
472                                 // splitting hairs we'd prefer to claim payments that were to us, but we haven't
473                                 // given up the preimage yet, so might as well just wait until the payment is
474                                 // retried, avoiding the on-chain fees.
475                                 return Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
476                         },
477                         ChannelMonitorUpdateErr::TemporaryFailure => {
478                                 $entry.get_mut().monitor_update_failed($action_type, $failed_forwards, $failed_fails, $raa_first_dropped_cs);
479                                 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore("Failed to update ChannelMonitor"), *$entry.key()));
480                         },
481                 }
482         }
483 }
484
485 // Does not break in case of TemporaryFailure!
486 macro_rules! maybe_break_monitor_err {
487         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
488                 match $err {
489                         ChannelMonitorUpdateErr::PermanentFailure => {
490                                 let (channel_id, mut chan) = $entry.remove_entry();
491                                 if let Some(short_id) = chan.get_short_channel_id() {
492                                         $channel_state.short_to_id.remove(&short_id);
493                                 }
494                                 break Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
495                         },
496                         ChannelMonitorUpdateErr::TemporaryFailure => {
497                                 $entry.get_mut().monitor_update_failed($action_type, Vec::new(), Vec::new(), false);
498                         },
499                 }
500         }
501 }
502
503 impl ChannelManager {
504         /// Constructs a new ChannelManager to hold several channels and route between them.
505         ///
506         /// This is the main "logic hub" for all channel-related actions, and implements
507         /// ChannelMessageHandler.
508         ///
509         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
510         ///
511         /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
512         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> {
513                 let secp_ctx = Secp256k1::new();
514
515                 let res = Arc::new(ChannelManager {
516                         default_configuration: config.clone(),
517                         genesis_hash: genesis_block(network).header.bitcoin_hash(),
518                         fee_estimator: feeest.clone(),
519                         monitor: monitor.clone(),
520                         chain_monitor,
521                         tx_broadcaster,
522
523                         latest_block_height: AtomicUsize::new(0), //TODO: Get an init value
524                         last_block_hash: Mutex::new(Default::default()),
525                         secp_ctx,
526
527                         channel_state: Mutex::new(ChannelHolder{
528                                 by_id: HashMap::new(),
529                                 short_to_id: HashMap::new(),
530                                 next_forward: Instant::now(),
531                                 forward_htlcs: HashMap::new(),
532                                 claimable_htlcs: HashMap::new(),
533                                 pending_msg_events: Vec::new(),
534                         }),
535                         our_network_key: keys_manager.get_node_secret(),
536
537                         pending_events: Mutex::new(Vec::new()),
538                         total_consistency_lock: RwLock::new(()),
539
540                         keys_manager,
541
542                         logger,
543                 });
544                 let weak_res = Arc::downgrade(&res);
545                 res.chain_monitor.register_listener(weak_res);
546                 Ok(res)
547         }
548
549         /// Creates a new outbound channel to the given remote node and with the given value.
550         ///
551         /// user_id will be provided back as user_channel_id in FundingGenerationReady and
552         /// FundingBroadcastSafe events to allow tracking of which events correspond with which
553         /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
554         /// may wish to avoid using 0 for user_id here.
555         ///
556         /// If successful, will generate a SendOpenChannel message event, so you should probably poll
557         /// PeerManager::process_events afterwards.
558         ///
559         /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
560         /// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
561         pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64) -> Result<(), APIError> {
562                 if channel_value_satoshis < 1000 {
563                         return Err(APIError::APIMisuseError { err: "channel_value must be at least 1000 satoshis" });
564                 }
565
566                 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)?;
567                 let res = channel.get_open_channel(self.genesis_hash.clone(), &*self.fee_estimator);
568
569                 let _ = self.total_consistency_lock.read().unwrap();
570                 let mut channel_state = self.channel_state.lock().unwrap();
571                 match channel_state.by_id.entry(channel.channel_id()) {
572                         hash_map::Entry::Occupied(_) => {
573                                 if cfg!(feature = "fuzztarget") {
574                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG" });
575                                 } else {
576                                         panic!("RNG is bad???");
577                                 }
578                         },
579                         hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
580                 }
581                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
582                         node_id: their_network_key,
583                         msg: res,
584                 });
585                 Ok(())
586         }
587
588         /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
589         /// more information.
590         pub fn list_channels(&self) -> Vec<ChannelDetails> {
591                 let channel_state = self.channel_state.lock().unwrap();
592                 let mut res = Vec::with_capacity(channel_state.by_id.len());
593                 for (channel_id, channel) in channel_state.by_id.iter() {
594                         res.push(ChannelDetails {
595                                 channel_id: (*channel_id).clone(),
596                                 short_channel_id: channel.get_short_channel_id(),
597                                 remote_network_id: channel.get_their_node_id(),
598                                 channel_value_satoshis: channel.get_value_satoshis(),
599                                 user_id: channel.get_user_id(),
600                         });
601                 }
602                 res
603         }
604
605         /// Gets the list of usable channels, in random order. Useful as an argument to
606         /// Router::get_route to ensure non-announced channels are used.
607         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
608                 let channel_state = self.channel_state.lock().unwrap();
609                 let mut res = Vec::with_capacity(channel_state.by_id.len());
610                 for (channel_id, channel) in channel_state.by_id.iter() {
611                         // Note we use is_live here instead of usable which leads to somewhat confused
612                         // internal/external nomenclature, but that's ok cause that's probably what the user
613                         // really wanted anyway.
614                         if channel.is_live() {
615                                 res.push(ChannelDetails {
616                                         channel_id: (*channel_id).clone(),
617                                         short_channel_id: channel.get_short_channel_id(),
618                                         remote_network_id: channel.get_their_node_id(),
619                                         channel_value_satoshis: channel.get_value_satoshis(),
620                                         user_id: channel.get_user_id(),
621                                 });
622                         }
623                 }
624                 res
625         }
626
627         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
628         /// will be accepted on the given channel, and after additional timeout/the closing of all
629         /// pending HTLCs, the channel will be closed on chain.
630         ///
631         /// May generate a SendShutdown message event on success, which should be relayed.
632         pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
633                 let _ = self.total_consistency_lock.read().unwrap();
634
635                 let (mut failed_htlcs, chan_option) = {
636                         let mut channel_state_lock = self.channel_state.lock().unwrap();
637                         let channel_state = channel_state_lock.borrow_parts();
638                         match channel_state.by_id.entry(channel_id.clone()) {
639                                 hash_map::Entry::Occupied(mut chan_entry) => {
640                                         let (shutdown_msg, failed_htlcs) = chan_entry.get_mut().get_shutdown()?;
641                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
642                                                 node_id: chan_entry.get().get_their_node_id(),
643                                                 msg: shutdown_msg
644                                         });
645                                         if chan_entry.get().is_shutdown() {
646                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
647                                                         channel_state.short_to_id.remove(&short_id);
648                                                 }
649                                                 (failed_htlcs, Some(chan_entry.remove_entry().1))
650                                         } else { (failed_htlcs, None) }
651                                 },
652                                 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: "No such channel"})
653                         }
654                 };
655                 for htlc_source in failed_htlcs.drain(..) {
656                         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() });
657                 }
658                 let chan_update = if let Some(chan) = chan_option {
659                         if let Ok(update) = self.get_channel_update(&chan) {
660                                 Some(update)
661                         } else { None }
662                 } else { None };
663
664                 if let Some(update) = chan_update {
665                         let mut channel_state = self.channel_state.lock().unwrap();
666                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
667                                 msg: update
668                         });
669                 }
670
671                 Ok(())
672         }
673
674         #[inline]
675         fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
676                 let (local_txn, mut failed_htlcs) = shutdown_res;
677                 log_trace!(self, "Finishing force-closure of channel with {} transactions to broadcast and {} HTLCs to fail", local_txn.len(), failed_htlcs.len());
678                 for htlc_source in failed_htlcs.drain(..) {
679                         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() });
680                 }
681                 for tx in local_txn {
682                         self.tx_broadcaster.broadcast_transaction(&tx);
683                 }
684         }
685
686         /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
687         /// the chain and rejecting new HTLCs on the given channel.
688         pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
689                 let _ = self.total_consistency_lock.read().unwrap();
690
691                 let mut chan = {
692                         let mut channel_state_lock = self.channel_state.lock().unwrap();
693                         let channel_state = channel_state_lock.borrow_parts();
694                         if let Some(chan) = channel_state.by_id.remove(channel_id) {
695                                 if let Some(short_id) = chan.get_short_channel_id() {
696                                         channel_state.short_to_id.remove(&short_id);
697                                 }
698                                 chan
699                         } else {
700                                 return;
701                         }
702                 };
703                 log_trace!(self, "Force-closing channel {}", log_bytes!(channel_id[..]));
704                 self.finish_force_close_channel(chan.force_shutdown());
705                 if let Ok(update) = self.get_channel_update(&chan) {
706                         let mut channel_state = self.channel_state.lock().unwrap();
707                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
708                                 msg: update
709                         });
710                 }
711         }
712
713         /// Force close all channels, immediately broadcasting the latest local commitment transaction
714         /// for each to the chain and rejecting new HTLCs on each.
715         pub fn force_close_all_channels(&self) {
716                 for chan in self.list_channels() {
717                         self.force_close_channel(&chan.channel_id);
718                 }
719         }
720
721         #[inline]
722         fn gen_rho_mu_from_shared_secret(shared_secret: &[u8]) -> ([u8; 32], [u8; 32]) {
723                 assert_eq!(shared_secret.len(), 32);
724                 ({
725                         let mut hmac = HmacEngine::<Sha256>::new(&[0x72, 0x68, 0x6f]); // rho
726                         hmac.input(&shared_secret[..]);
727                         Hmac::from_engine(hmac).into_inner()
728                 },
729                 {
730                         let mut hmac = HmacEngine::<Sha256>::new(&[0x6d, 0x75]); // mu
731                         hmac.input(&shared_secret[..]);
732                         Hmac::from_engine(hmac).into_inner()
733                 })
734         }
735
736         #[inline]
737         fn gen_um_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
738                 assert_eq!(shared_secret.len(), 32);
739                 let mut hmac = HmacEngine::<Sha256>::new(&[0x75, 0x6d]); // um
740                 hmac.input(&shared_secret[..]);
741                 Hmac::from_engine(hmac).into_inner()
742         }
743
744         #[inline]
745         fn gen_ammag_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
746                 assert_eq!(shared_secret.len(), 32);
747                 let mut hmac = HmacEngine::<Sha256>::new(&[0x61, 0x6d, 0x6d, 0x61, 0x67]); // ammag
748                 hmac.input(&shared_secret[..]);
749                 Hmac::from_engine(hmac).into_inner()
750         }
751
752         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
753         #[inline]
754         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> {
755                 let mut blinded_priv = session_priv.clone();
756                 let mut blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
757
758                 for hop in route.hops.iter() {
759                         let shared_secret = SharedSecret::new(secp_ctx, &hop.pubkey, &blinded_priv);
760
761                         let mut sha = Sha256::engine();
762                         sha.input(&blinded_pub.serialize()[..]);
763                         sha.input(&shared_secret[..]);
764                         let blinding_factor = Sha256::from_engine(sha).into_inner();
765
766                         let ephemeral_pubkey = blinded_pub;
767
768                         blinded_priv.mul_assign(secp_ctx, &SecretKey::from_slice(secp_ctx, &blinding_factor)?)?;
769                         blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
770
771                         callback(shared_secret, blinding_factor, ephemeral_pubkey, hop);
772                 }
773
774                 Ok(())
775         }
776
777         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
778         fn construct_onion_keys<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey) -> Result<Vec<OnionKeys>, secp256k1::Error> {
779                 let mut res = Vec::with_capacity(route.hops.len());
780
781                 Self::construct_onion_keys_callback(secp_ctx, route, session_priv, |shared_secret, _blinding_factor, ephemeral_pubkey, _| {
782                         let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret[..]);
783
784                         res.push(OnionKeys {
785                                 #[cfg(test)]
786                                 shared_secret,
787                                 #[cfg(test)]
788                                 blinding_factor: _blinding_factor,
789                                 ephemeral_pubkey,
790                                 rho,
791                                 mu,
792                         });
793                 })?;
794
795                 Ok(res)
796         }
797
798         /// returns the hop data, as well as the first-hop value_msat and CLTV value we should send.
799         fn build_onion_payloads(route: &Route, starting_htlc_offset: u32) -> Result<(Vec<msgs::OnionHopData>, u64, u32), APIError> {
800                 let mut cur_value_msat = 0u64;
801                 let mut cur_cltv = starting_htlc_offset;
802                 let mut last_short_channel_id = 0;
803                 let mut res: Vec<msgs::OnionHopData> = Vec::with_capacity(route.hops.len());
804                 internal_traits::test_no_dealloc::<msgs::OnionHopData>(None);
805                 unsafe { res.set_len(route.hops.len()); }
806
807                 for (idx, hop) in route.hops.iter().enumerate().rev() {
808                         // First hop gets special values so that it can check, on receipt, that everything is
809                         // exactly as it should be (and the next hop isn't trying to probe to find out if we're
810                         // the intended recipient).
811                         let value_msat = if cur_value_msat == 0 { hop.fee_msat } else { cur_value_msat };
812                         let cltv = if cur_cltv == starting_htlc_offset { hop.cltv_expiry_delta + starting_htlc_offset } else { cur_cltv };
813                         res[idx] = msgs::OnionHopData {
814                                 realm: 0,
815                                 data: msgs::OnionRealm0HopData {
816                                         short_channel_id: last_short_channel_id,
817                                         amt_to_forward: value_msat,
818                                         outgoing_cltv_value: cltv,
819                                 },
820                                 hmac: [0; 32],
821                         };
822                         cur_value_msat += hop.fee_msat;
823                         if cur_value_msat >= 21000000 * 100000000 * 1000 {
824                                 return Err(APIError::RouteError{err: "Channel fees overflowed?!"});
825                         }
826                         cur_cltv += hop.cltv_expiry_delta as u32;
827                         if cur_cltv >= 500000000 {
828                                 return Err(APIError::RouteError{err: "Channel CLTV overflowed?!"});
829                         }
830                         last_short_channel_id = hop.short_channel_id;
831                 }
832                 Ok((res, cur_value_msat, cur_cltv))
833         }
834
835         #[inline]
836         fn shift_arr_right(arr: &mut [u8; 20*65]) {
837                 unsafe {
838                         ptr::copy(arr[0..].as_ptr(), arr[65..].as_mut_ptr(), 19*65);
839                 }
840                 for i in 0..65 {
841                         arr[i] = 0;
842                 }
843         }
844
845         #[inline]
846         fn xor_bufs(dst: &mut[u8], src: &[u8]) {
847                 assert_eq!(dst.len(), src.len());
848
849                 for i in 0..dst.len() {
850                         dst[i] ^= src[i];
851                 }
852         }
853
854         const ZERO:[u8; 21*65] = [0; 21*65];
855         fn construct_onion_packet(mut payloads: Vec<msgs::OnionHopData>, onion_keys: Vec<OnionKeys>, associated_data: &PaymentHash) -> msgs::OnionPacket {
856                 let mut buf = Vec::with_capacity(21*65);
857                 buf.resize(21*65, 0);
858
859                 let filler = {
860                         let iters = payloads.len() - 1;
861                         let end_len = iters * 65;
862                         let mut res = Vec::with_capacity(end_len);
863                         res.resize(end_len, 0);
864
865                         for (i, keys) in onion_keys.iter().enumerate() {
866                                 if i == payloads.len() - 1 { continue; }
867                                 let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
868                                 chacha.process(&ChannelManager::ZERO, &mut buf); // We don't have a seek function :(
869                                 ChannelManager::xor_bufs(&mut res[0..(i + 1)*65], &buf[(20 - i)*65..21*65]);
870                         }
871                         res
872                 };
873
874                 let mut packet_data = [0; 20*65];
875                 let mut hmac_res = [0; 32];
876
877                 for (i, (payload, keys)) in payloads.iter_mut().zip(onion_keys.iter()).rev().enumerate() {
878                         ChannelManager::shift_arr_right(&mut packet_data);
879                         payload.hmac = hmac_res;
880                         packet_data[0..65].copy_from_slice(&payload.encode()[..]);
881
882                         let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
883                         chacha.process(&packet_data, &mut buf[0..20*65]);
884                         packet_data[..].copy_from_slice(&buf[0..20*65]);
885
886                         if i == 0 {
887                                 packet_data[20*65 - filler.len()..20*65].copy_from_slice(&filler[..]);
888                         }
889
890                         let mut hmac = HmacEngine::<Sha256>::new(&keys.mu);
891                         hmac.input(&packet_data);
892                         hmac.input(&associated_data.0[..]);
893                         hmac_res = Hmac::from_engine(hmac).into_inner();
894                 }
895
896                 msgs::OnionPacket{
897                         version: 0,
898                         public_key: Ok(onion_keys.first().unwrap().ephemeral_pubkey),
899                         hop_data: packet_data,
900                         hmac: hmac_res,
901                 }
902         }
903
904         /// Encrypts a failure packet. raw_packet can either be a
905         /// msgs::DecodedOnionErrorPacket.encode() result or a msgs::OnionErrorPacket.data element.
906         fn encrypt_failure_packet(shared_secret: &[u8], raw_packet: &[u8]) -> msgs::OnionErrorPacket {
907                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
908
909                 let mut packet_crypted = Vec::with_capacity(raw_packet.len());
910                 packet_crypted.resize(raw_packet.len(), 0);
911                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
912                 chacha.process(&raw_packet, &mut packet_crypted[..]);
913                 msgs::OnionErrorPacket {
914                         data: packet_crypted,
915                 }
916         }
917
918         fn build_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::DecodedOnionErrorPacket {
919                 assert_eq!(shared_secret.len(), 32);
920                 assert!(failure_data.len() <= 256 - 2);
921
922                 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
923
924                 let failuremsg = {
925                         let mut res = Vec::with_capacity(2 + failure_data.len());
926                         res.push(((failure_type >> 8) & 0xff) as u8);
927                         res.push(((failure_type >> 0) & 0xff) as u8);
928                         res.extend_from_slice(&failure_data[..]);
929                         res
930                 };
931                 let pad = {
932                         let mut res = Vec::with_capacity(256 - 2 - failure_data.len());
933                         res.resize(256 - 2 - failure_data.len(), 0);
934                         res
935                 };
936                 let mut packet = msgs::DecodedOnionErrorPacket {
937                         hmac: [0; 32],
938                         failuremsg: failuremsg,
939                         pad: pad,
940                 };
941
942                 let mut hmac = HmacEngine::<Sha256>::new(&um);
943                 hmac.input(&packet.encode()[32..]);
944                 packet.hmac = Hmac::from_engine(hmac).into_inner();
945
946                 packet
947         }
948
949         #[inline]
950         fn build_first_hop_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::OnionErrorPacket {
951                 let failure_packet = ChannelManager::build_failure_packet(shared_secret, failure_type, failure_data);
952                 ChannelManager::encrypt_failure_packet(shared_secret, &failure_packet.encode()[..])
953         }
954
955         fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder>) {
956                 macro_rules! return_malformed_err {
957                         ($msg: expr, $err_code: expr) => {
958                                 {
959                                         log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
960                                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
961                                                 channel_id: msg.channel_id,
962                                                 htlc_id: msg.htlc_id,
963                                                 sha256_of_onion: Sha256::hash(&msg.onion_routing_packet.hop_data).into_inner(),
964                                                 failure_code: $err_code,
965                                         })), self.channel_state.lock().unwrap());
966                                 }
967                         }
968                 }
969
970                 if let Err(_) = msg.onion_routing_packet.public_key {
971                         return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
972                 }
973
974                 let shared_secret = {
975                         let mut arr = [0; 32];
976                         arr.copy_from_slice(&SharedSecret::new(&self.secp_ctx, &msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key)[..]);
977                         arr
978                 };
979                 let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
980
981                 if msg.onion_routing_packet.version != 0 {
982                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
983                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
984                         //the hash doesn't really serve any purpuse - in the case of hashing all data, the
985                         //receiving node would have to brute force to figure out which version was put in the
986                         //packet by the node that send us the message, in the case of hashing the hop_data, the
987                         //node knows the HMAC matched, so they already know what is there...
988                         return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
989                 }
990
991
992                 let mut hmac = HmacEngine::<Sha256>::new(&mu);
993                 hmac.input(&msg.onion_routing_packet.hop_data);
994                 hmac.input(&msg.payment_hash.0[..]);
995                 if !crypto::util::fixed_time_eq(&Hmac::from_engine(hmac).into_inner(), &msg.onion_routing_packet.hmac) {
996                         return_malformed_err!("HMAC Check failed", 0x8000 | 0x4000 | 5);
997                 }
998
999                 let mut channel_state = None;
1000                 macro_rules! return_err {
1001                         ($msg: expr, $err_code: expr, $data: expr) => {
1002                                 {
1003                                         log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
1004                                         if channel_state.is_none() {
1005                                                 channel_state = Some(self.channel_state.lock().unwrap());
1006                                         }
1007                                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
1008                                                 channel_id: msg.channel_id,
1009                                                 htlc_id: msg.htlc_id,
1010                                                 reason: ChannelManager::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
1011                                         })), channel_state.unwrap());
1012                                 }
1013                         }
1014                 }
1015
1016                 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
1017                 let next_hop_data = {
1018                         let mut decoded = [0; 65];
1019                         chacha.process(&msg.onion_routing_packet.hop_data[0..65], &mut decoded);
1020                         match msgs::OnionHopData::read(&mut Cursor::new(&decoded[..])) {
1021                                 Err(err) => {
1022                                         let error_code = match err {
1023                                                 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
1024                                                 _ => 0x2000 | 2, // Should never happen
1025                                         };
1026                                         return_err!("Unable to decode our hop data", error_code, &[0;0]);
1027                                 },
1028                                 Ok(msg) => msg
1029                         }
1030                 };
1031
1032                 let pending_forward_info = if next_hop_data.hmac == [0; 32] {
1033                                 // OUR PAYMENT!
1034                                 // final_expiry_too_soon
1035                                 if (msg.cltv_expiry as u64) < self.latest_block_height.load(Ordering::Acquire) as u64 + (CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS) as u64 {
1036                                         return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
1037                                 }
1038                                 // final_incorrect_htlc_amount
1039                                 if next_hop_data.data.amt_to_forward > msg.amount_msat {
1040                                         return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
1041                                 }
1042                                 // final_incorrect_cltv_expiry
1043                                 if next_hop_data.data.outgoing_cltv_value != msg.cltv_expiry {
1044                                         return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
1045                                 }
1046
1047                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
1048                                 // message, however that would leak that we are the recipient of this payment, so
1049                                 // instead we stay symmetric with the forwarding case, only responding (after a
1050                                 // delay) once they've send us a commitment_signed!
1051
1052                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1053                                         onion_packet: None,
1054                                         payment_hash: msg.payment_hash.clone(),
1055                                         short_channel_id: 0,
1056                                         incoming_shared_secret: shared_secret,
1057                                         amt_to_forward: next_hop_data.data.amt_to_forward,
1058                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1059                                 })
1060                         } else {
1061                                 let mut new_packet_data = [0; 20*65];
1062                                 chacha.process(&msg.onion_routing_packet.hop_data[65..], &mut new_packet_data[0..19*65]);
1063                                 chacha.process(&ChannelManager::ZERO[0..65], &mut new_packet_data[19*65..]);
1064
1065                                 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
1066
1067                                 let blinding_factor = {
1068                                         let mut sha = Sha256::engine();
1069                                         sha.input(&new_pubkey.serialize()[..]);
1070                                         sha.input(&shared_secret);
1071                                         SecretKey::from_slice(&self.secp_ctx, &Sha256::from_engine(sha).into_inner()).expect("SHA-256 is broken?")
1072                                 };
1073
1074                                 let public_key = if let Err(e) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor) {
1075                                         Err(e)
1076                                 } else { Ok(new_pubkey) };
1077
1078                                 let outgoing_packet = msgs::OnionPacket {
1079                                         version: 0,
1080                                         public_key,
1081                                         hop_data: new_packet_data,
1082                                         hmac: next_hop_data.hmac.clone(),
1083                                 };
1084
1085                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1086                                         onion_packet: Some(outgoing_packet),
1087                                         payment_hash: msg.payment_hash.clone(),
1088                                         short_channel_id: next_hop_data.data.short_channel_id,
1089                                         incoming_shared_secret: shared_secret,
1090                                         amt_to_forward: next_hop_data.data.amt_to_forward,
1091                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1092                                 })
1093                         };
1094
1095                 channel_state = Some(self.channel_state.lock().unwrap());
1096                 if let &PendingHTLCStatus::Forward(PendingForwardHTLCInfo { ref onion_packet, ref short_channel_id, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
1097                         if onion_packet.is_some() { // If short_channel_id is 0 here, we'll reject them in the body here
1098                                 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
1099                                 let forwarding_id = match id_option {
1100                                         None => { // unknown_next_peer
1101                                                 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
1102                                         },
1103                                         Some(id) => id.clone(),
1104                                 };
1105                                 if let Some((err, code, chan_update)) = loop {
1106                                         let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
1107
1108                                         // Note that we could technically not return an error yet here and just hope
1109                                         // that the connection is reestablished or monitor updated by the time we get
1110                                         // around to doing the actual forward, but better to fail early if we can and
1111                                         // hopefully an attacker trying to path-trace payments cannot make this occur
1112                                         // on a small/per-node/per-channel scale.
1113                                         if !chan.is_live() { // channel_disabled
1114                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
1115                                         }
1116                                         if *amt_to_forward < chan.get_their_htlc_minimum_msat() { // amount_below_minimum
1117                                                 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
1118                                         }
1119                                         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) });
1120                                         if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
1121                                                 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())));
1122                                         }
1123                                         if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 { // incorrect_cltv_expiry
1124                                                 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())));
1125                                         }
1126                                         let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1127                                         // We want to have at least HTLC_FAIL_TIMEOUT_BLOCKS to fail prior to going on chain CLAIM_BUFFER blocks before expiration
1128                                         if msg.cltv_expiry <= cur_height + CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS as u32 { // expiry_too_soon
1129                                                 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1130                                         }
1131                                         if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
1132                                                 break Some(("CLTV expiry is too far in the future", 21, None));
1133                                         }
1134                                         break None;
1135                                 }
1136                                 {
1137                                         let mut res = Vec::with_capacity(8 + 128);
1138                                         if let Some(chan_update) = chan_update {
1139                                                 if code == 0x1000 | 11 || code == 0x1000 | 12 {
1140                                                         res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
1141                                                 }
1142                                                 else if code == 0x1000 | 13 {
1143                                                         res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
1144                                                 }
1145                                                 else if code == 0x1000 | 20 {
1146                                                         res.extend_from_slice(&byte_utils::be16_to_array(chan_update.contents.flags));
1147                                                 }
1148                                                 res.extend_from_slice(&chan_update.encode_with_len()[..]);
1149                                         }
1150                                         return_err!(err, code, &res[..]);
1151                                 }
1152                         }
1153                 }
1154
1155                 (pending_forward_info, channel_state.unwrap())
1156         }
1157
1158         /// only fails if the channel does not yet have an assigned short_id
1159         /// May be called with channel_state already locked!
1160         fn get_channel_update(&self, chan: &Channel) -> Result<msgs::ChannelUpdate, HandleError> {
1161                 let short_channel_id = match chan.get_short_channel_id() {
1162                         None => return Err(HandleError{err: "Channel not yet established", action: None}),
1163                         Some(id) => id,
1164                 };
1165
1166                 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_their_node_id().serialize()[..];
1167
1168                 let unsigned = msgs::UnsignedChannelUpdate {
1169                         chain_hash: self.genesis_hash,
1170                         short_channel_id: short_channel_id,
1171                         timestamp: chan.get_channel_update_count(),
1172                         flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
1173                         cltv_expiry_delta: CLTV_EXPIRY_DELTA,
1174                         htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
1175                         fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
1176                         fee_proportional_millionths: chan.get_fee_proportional_millionths(),
1177                         excess_data: Vec::new(),
1178                 };
1179
1180                 let msg_hash = Sha256dHash::from_data(&unsigned.encode()[..]);
1181                 let sig = self.secp_ctx.sign(&Message::from_slice(&msg_hash[..]).unwrap(), &self.our_network_key);
1182
1183                 Ok(msgs::ChannelUpdate {
1184                         signature: sig,
1185                         contents: unsigned
1186                 })
1187         }
1188
1189         /// Sends a payment along a given route.
1190         ///
1191         /// Value parameters are provided via the last hop in route, see documentation for RouteHop
1192         /// fields for more info.
1193         ///
1194         /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
1195         /// payment), we don't do anything to stop you! We always try to ensure that if the provided
1196         /// next hop knows the preimage to payment_hash they can claim an additional amount as
1197         /// specified in the last hop in the route! Thus, you should probably do your own
1198         /// payment_preimage tracking (which you should already be doing as they represent "proof of
1199         /// payment") and prevent double-sends yourself.
1200         ///
1201         /// May generate a SendHTLCs message event on success, which should be relayed.
1202         ///
1203         /// Raises APIError::RoutError when invalid route or forward parameter
1204         /// (cltv_delta, fee, node public key) is specified.
1205         /// Raises APIError::ChannelUnavailable if the next-hop channel is not available for updates
1206         /// (including due to previous monitor update failure or new permanent monitor update failure).
1207         /// Raised APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
1208         /// relevant updates.
1209         ///
1210         /// In case of APIError::RouteError/APIError::ChannelUnavailable, the payment send has failed
1211         /// and you may wish to retry via a different route immediately.
1212         /// In case of APIError::MonitorUpdateFailed, the commitment update has been irrevocably
1213         /// committed on our end and we're just waiting for a monitor update to send it. Do NOT retry
1214         /// the payment via a different route unless you intend to pay twice!
1215         pub fn send_payment(&self, route: Route, payment_hash: PaymentHash) -> Result<(), APIError> {
1216                 if route.hops.len() < 1 || route.hops.len() > 20 {
1217                         return Err(APIError::RouteError{err: "Route didn't go anywhere/had bogus size"});
1218                 }
1219                 let our_node_id = self.get_our_node_id();
1220                 for (idx, hop) in route.hops.iter().enumerate() {
1221                         if idx != route.hops.len() - 1 && hop.pubkey == our_node_id {
1222                                 return Err(APIError::RouteError{err: "Route went through us but wasn't a simple rebalance loop to us"});
1223                         }
1224                 }
1225
1226                 let session_priv = self.keys_manager.get_session_key();
1227
1228                 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1229
1230                 let onion_keys = secp_call!(ChannelManager::construct_onion_keys(&self.secp_ctx, &route, &session_priv),
1231                                 APIError::RouteError{err: "Pubkey along hop was maliciously selected"});
1232                 let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height)?;
1233                 let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
1234
1235                 let _ = self.total_consistency_lock.read().unwrap();
1236
1237                 let err: Result<(), _> = loop {
1238                         let mut channel_lock = self.channel_state.lock().unwrap();
1239
1240                         let id = match channel_lock.short_to_id.get(&route.hops.first().unwrap().short_channel_id) {
1241                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!"}),
1242                                 Some(id) => id.clone(),
1243                         };
1244
1245                         let channel_state = channel_lock.borrow_parts();
1246                         if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) {
1247                                 match {
1248                                         if chan.get().get_their_node_id() != route.hops.first().unwrap().pubkey {
1249                                                 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1250                                         }
1251                                         if !chan.get().is_live() {
1252                                                 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!"});
1253                                         }
1254                                         break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1255                                                 route: route.clone(),
1256                                                 session_priv: session_priv.clone(),
1257                                                 first_hop_htlc_msat: htlc_msat,
1258                                         }, onion_packet), channel_state, chan)
1259                                 } {
1260                                         Some((update_add, commitment_signed, chan_monitor)) => {
1261                                                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1262                                                         maybe_break_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst);
1263                                                         // Note that MonitorUpdateFailed here indicates (per function docs)
1264                                                         // that we will resent the commitment update once we unfree monitor
1265                                                         // updating, so we have to take special care that we don't return
1266                                                         // something else in case we will resend later!
1267                                                         return Err(APIError::MonitorUpdateFailed);
1268                                                 }
1269
1270                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1271                                                         node_id: route.hops.first().unwrap().pubkey,
1272                                                         updates: msgs::CommitmentUpdate {
1273                                                                 update_add_htlcs: vec![update_add],
1274                                                                 update_fulfill_htlcs: Vec::new(),
1275                                                                 update_fail_htlcs: Vec::new(),
1276                                                                 update_fail_malformed_htlcs: Vec::new(),
1277                                                                 update_fee: None,
1278                                                                 commitment_signed,
1279                                                         },
1280                                                 });
1281                                         },
1282                                         None => {},
1283                                 }
1284                         } else { unreachable!(); }
1285                         return Ok(());
1286                 };
1287
1288                 match handle_error!(self, err, route.hops.first().unwrap().pubkey) {
1289                         Ok(_) => unreachable!(),
1290                         Err(e) => {
1291                                 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
1292                                 } else {
1293                                         log_error!(self, "Got bad keys: {}!", e.err);
1294                                         let mut channel_state = self.channel_state.lock().unwrap();
1295                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1296                                                 node_id: route.hops.first().unwrap().pubkey,
1297                                                 action: e.action,
1298                                         });
1299                                 }
1300                                 Err(APIError::ChannelUnavailable { err: e.err })
1301                         },
1302                 }
1303         }
1304
1305         /// Call this upon creation of a funding transaction for the given channel.
1306         ///
1307         /// Note that ALL inputs in the transaction pointed to by funding_txo MUST spend SegWit outputs
1308         /// or your counterparty can steal your funds!
1309         ///
1310         /// Panics if a funding transaction has already been provided for this channel.
1311         ///
1312         /// May panic if the funding_txo is duplicative with some other channel (note that this should
1313         /// be trivially prevented by using unique funding transaction keys per-channel).
1314         pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1315                 let _ = self.total_consistency_lock.read().unwrap();
1316
1317                 let (chan, msg, chan_monitor) = {
1318                         let (res, chan) = {
1319                                 let mut channel_state = self.channel_state.lock().unwrap();
1320                                 match channel_state.by_id.remove(temporary_channel_id) {
1321                                         Some(mut chan) => {
1322                                                 (chan.get_outbound_funding_created(funding_txo)
1323                                                         .map_err(|e| if let ChannelError::Close(msg) = e {
1324                                                                 MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.force_shutdown(), None)
1325                                                         } else { unreachable!(); })
1326                                                 , chan)
1327                                         },
1328                                         None => return
1329                                 }
1330                         };
1331                         match handle_error!(self, res, chan.get_their_node_id()) {
1332                                 Ok(funding_msg) => {
1333                                         (chan, funding_msg.0, funding_msg.1)
1334                                 },
1335                                 Err(e) => {
1336                                         log_error!(self, "Got bad signatures: {}!", e.err);
1337                                         let mut channel_state = self.channel_state.lock().unwrap();
1338                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1339                                                 node_id: chan.get_their_node_id(),
1340                                                 action: e.action,
1341                                         });
1342                                         return;
1343                                 },
1344                         }
1345                 };
1346                 // Because we have exclusive ownership of the channel here we can release the channel_state
1347                 // lock before add_update_monitor
1348                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1349                         unimplemented!();
1350                 }
1351
1352                 let mut channel_state = self.channel_state.lock().unwrap();
1353                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
1354                         node_id: chan.get_their_node_id(),
1355                         msg: msg,
1356                 });
1357                 match channel_state.by_id.entry(chan.channel_id()) {
1358                         hash_map::Entry::Occupied(_) => {
1359                                 panic!("Generated duplicate funding txid?");
1360                         },
1361                         hash_map::Entry::Vacant(e) => {
1362                                 e.insert(chan);
1363                         }
1364                 }
1365         }
1366
1367         fn get_announcement_sigs(&self, chan: &Channel) -> Option<msgs::AnnouncementSignatures> {
1368                 if !chan.should_announce() { return None }
1369
1370                 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1371                         Ok(res) => res,
1372                         Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1373                 };
1374                 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
1375                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1376
1377                 Some(msgs::AnnouncementSignatures {
1378                         channel_id: chan.channel_id(),
1379                         short_channel_id: chan.get_short_channel_id().unwrap(),
1380                         node_signature: our_node_sig,
1381                         bitcoin_signature: our_bitcoin_sig,
1382                 })
1383         }
1384
1385         /// Processes HTLCs which are pending waiting on random forward delay.
1386         ///
1387         /// Should only really ever be called in response to an PendingHTLCsForwardable event.
1388         /// Will likely generate further events.
1389         pub fn process_pending_htlc_forwards(&self) {
1390                 let _ = self.total_consistency_lock.read().unwrap();
1391
1392                 let mut new_events = Vec::new();
1393                 let mut failed_forwards = Vec::new();
1394                 {
1395                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1396                         let channel_state = channel_state_lock.borrow_parts();
1397
1398                         if cfg!(not(feature = "fuzztarget")) && Instant::now() < *channel_state.next_forward {
1399                                 return;
1400                         }
1401
1402                         for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1403                                 if short_chan_id != 0 {
1404                                         let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1405                                                 Some(chan_id) => chan_id.clone(),
1406                                                 None => {
1407                                                         failed_forwards.reserve(pending_forwards.len());
1408                                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1409                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1410                                                                         short_channel_id: prev_short_channel_id,
1411                                                                         htlc_id: prev_htlc_id,
1412                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1413                                                                 });
1414                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
1415                                                         }
1416                                                         continue;
1417                                                 }
1418                                         };
1419                                         let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();
1420
1421                                         let mut add_htlc_msgs = Vec::new();
1422                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1423                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1424                                                         short_channel_id: prev_short_channel_id,
1425                                                         htlc_id: prev_htlc_id,
1426                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1427                                                 });
1428                                                 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()) {
1429                                                         Err(_e) => {
1430                                                                 let chan_update = self.get_channel_update(forward_chan).unwrap();
1431                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x1000 | 7, Some(chan_update)));
1432                                                                 continue;
1433                                                         },
1434                                                         Ok(update_add) => {
1435                                                                 match update_add {
1436                                                                         Some(msg) => { add_htlc_msgs.push(msg); },
1437                                                                         None => {
1438                                                                                 // Nothing to do here...we're waiting on a remote
1439                                                                                 // revoke_and_ack before we can add anymore HTLCs. The Channel
1440                                                                                 // will automatically handle building the update_add_htlc and
1441                                                                                 // commitment_signed messages when we can.
1442                                                                                 // TODO: Do some kind of timer to set the channel as !is_live()
1443                                                                                 // as we don't really want others relying on us relaying through
1444                                                                                 // this channel currently :/.
1445                                                                         }
1446                                                                 }
1447                                                         }
1448                                                 }
1449                                         }
1450
1451                                         if !add_htlc_msgs.is_empty() {
1452                                                 let (commitment_msg, monitor) = match forward_chan.send_commitment() {
1453                                                         Ok(res) => res,
1454                                                         Err(e) => {
1455                                                                 if let ChannelError::Ignore(_) = e {
1456                                                                         panic!("Stated return value requirements in send_commitment() were not met");
1457                                                                 }
1458                                                                 //TODO: Handle...this is bad!
1459                                                                 continue;
1460                                                         },
1461                                                 };
1462                                                 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
1463                                                         unimplemented!();
1464                                                 }
1465                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1466                                                         node_id: forward_chan.get_their_node_id(),
1467                                                         updates: msgs::CommitmentUpdate {
1468                                                                 update_add_htlcs: add_htlc_msgs,
1469                                                                 update_fulfill_htlcs: Vec::new(),
1470                                                                 update_fail_htlcs: Vec::new(),
1471                                                                 update_fail_malformed_htlcs: Vec::new(),
1472                                                                 update_fee: None,
1473                                                                 commitment_signed: commitment_msg,
1474                                                         },
1475                                                 });
1476                                         }
1477                                 } else {
1478                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1479                                                 let prev_hop_data = HTLCPreviousHopData {
1480                                                         short_channel_id: prev_short_channel_id,
1481                                                         htlc_id: prev_htlc_id,
1482                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1483                                                 };
1484                                                 match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
1485                                                         hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(prev_hop_data),
1486                                                         hash_map::Entry::Vacant(entry) => { entry.insert(vec![prev_hop_data]); },
1487                                                 };
1488                                                 new_events.push(events::Event::PaymentReceived {
1489                                                         payment_hash: forward_info.payment_hash,
1490                                                         amt: forward_info.amt_to_forward,
1491                                                 });
1492                                         }
1493                                 }
1494                         }
1495                 }
1496
1497                 for (htlc_source, payment_hash, failure_code, update) in failed_forwards.drain(..) {
1498                         match update {
1499                                 None => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code, data: Vec::new() }),
1500                                 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() }),
1501                         };
1502                 }
1503
1504                 if new_events.is_empty() { return }
1505                 let mut events = self.pending_events.lock().unwrap();
1506                 events.append(&mut new_events);
1507         }
1508
1509         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
1510         /// after a PaymentReceived event.
1511         /// expected_value is the value you expected the payment to be for (not the amount it actually
1512         /// was for from the PaymentReceived event).
1513         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash, expected_value: u64) -> bool {
1514                 let _ = self.total_consistency_lock.read().unwrap();
1515
1516                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1517                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(payment_hash);
1518                 if let Some(mut sources) = removed_source {
1519                         for htlc_with_hash in sources.drain(..) {
1520                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1521                                 self.fail_htlc_backwards_internal(channel_state.take().unwrap(),
1522                                                 HTLCSource::PreviousHopData(htlc_with_hash), payment_hash,
1523                                                 HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: byte_utils::be64_to_array(expected_value).to_vec() });
1524                         }
1525                         true
1526                 } else { false }
1527         }
1528
1529         /// Fails an HTLC backwards to the sender of it to us.
1530         /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
1531         /// There are several callsites that do stupid things like loop over a list of payment_hashes
1532         /// to fail and take the channel_state lock for each iteration (as we take ownership and may
1533         /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
1534         /// still-available channels.
1535         fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
1536                 match source {
1537                         HTLCSource::OutboundRoute { ref route, .. } => {
1538                                 log_trace!(self, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1539                                 mem::drop(channel_state_lock);
1540                                 match &onion_error {
1541                                         &HTLCFailReason::ErrorPacket { ref err } => {
1542 #[cfg(test)]
1543                                                 let (channel_update, payment_retryable, onion_error_code) = self.process_onion_failure(&source, err.data.clone());
1544 #[cfg(not(test))]
1545                                                 let (channel_update, payment_retryable, _) = self.process_onion_failure(&source, err.data.clone());
1546                                                 // TODO: If we decided to blame ourselves (or one of our channels) in
1547                                                 // process_onion_failure we should close that channel as it implies our
1548                                                 // next-hop is needlessly blaming us!
1549                                                 if let Some(update) = channel_update {
1550                                                         self.channel_state.lock().unwrap().pending_msg_events.push(
1551                                                                 events::MessageSendEvent::PaymentFailureNetworkUpdate {
1552                                                                         update,
1553                                                                 }
1554                                                         );
1555                                                 }
1556                                                 self.pending_events.lock().unwrap().push(
1557                                                         events::Event::PaymentFailed {
1558                                                                 payment_hash: payment_hash.clone(),
1559                                                                 rejected_by_dest: !payment_retryable,
1560 #[cfg(test)]
1561                                                                 error_code: onion_error_code
1562                                                         }
1563                                                 );
1564                                         },
1565                                         &HTLCFailReason::Reason {
1566 #[cfg(test)]
1567                                                         ref failure_code,
1568                                                         .. } => {
1569                                                 // we get a fail_malformed_htlc from the first hop
1570                                                 // TODO: We'd like to generate a PaymentFailureNetworkUpdate for temporary
1571                                                 // failures here, but that would be insufficient as Router::get_route
1572                                                 // generally ignores its view of our own channels as we provide them via
1573                                                 // ChannelDetails.
1574                                                 // TODO: For non-temporary failures, we really should be closing the
1575                                                 // channel here as we apparently can't relay through them anyway.
1576                                                 self.pending_events.lock().unwrap().push(
1577                                                         events::Event::PaymentFailed {
1578                                                                 payment_hash: payment_hash.clone(),
1579                                                                 rejected_by_dest: route.hops.len() == 1,
1580 #[cfg(test)]
1581                                                                 error_code: Some(*failure_code),
1582                                                         }
1583                                                 );
1584                                         }
1585                                 }
1586                         },
1587                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
1588                                 let err_packet = match onion_error {
1589                                         HTLCFailReason::Reason { failure_code, data } => {
1590                                                 log_trace!(self, "Failing HTLC with payment_hash {} backwards from us with code {}", log_bytes!(payment_hash.0), failure_code);
1591                                                 let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1592                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1593                                         },
1594                                         HTLCFailReason::ErrorPacket { err } => {
1595                                                 log_trace!(self, "Failing HTLC with payment_hash {} backwards with pre-built ErrorPacket", log_bytes!(payment_hash.0));
1596                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1597                                         }
1598                                 };
1599
1600                                 let channel_state = channel_state_lock.borrow_parts();
1601
1602                                 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1603                                         Some(chan_id) => chan_id.clone(),
1604                                         None => return
1605                                 };
1606
1607                                 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1608                                 match chan.get_update_fail_htlc_and_commit(htlc_id, err_packet) {
1609                                         Ok(Some((msg, commitment_msg, chan_monitor))) => {
1610                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1611                                                         unimplemented!();
1612                                                 }
1613                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1614                                                         node_id: chan.get_their_node_id(),
1615                                                         updates: msgs::CommitmentUpdate {
1616                                                                 update_add_htlcs: Vec::new(),
1617                                                                 update_fulfill_htlcs: Vec::new(),
1618                                                                 update_fail_htlcs: vec![msg],
1619                                                                 update_fail_malformed_htlcs: Vec::new(),
1620                                                                 update_fee: None,
1621                                                                 commitment_signed: commitment_msg,
1622                                                         },
1623                                                 });
1624                                         },
1625                                         Ok(None) => {},
1626                                         Err(_e) => {
1627                                                 //TODO: Do something with e?
1628                                                 return;
1629                                         },
1630                                 }
1631                         },
1632                 }
1633         }
1634
1635         /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1636         /// generating message events for the net layer to claim the payment, if possible. Thus, you
1637         /// should probably kick the net layer to go send messages if this returns true!
1638         ///
1639         /// May panic if called except in response to a PaymentReceived event.
1640         pub fn claim_funds(&self, payment_preimage: PaymentPreimage) -> bool {
1641                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1642
1643                 let _ = self.total_consistency_lock.read().unwrap();
1644
1645                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1646                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&payment_hash);
1647                 if let Some(mut sources) = removed_source {
1648                         for htlc_with_hash in sources.drain(..) {
1649                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1650                                 self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_preimage);
1651                         }
1652                         true
1653                 } else { false }
1654         }
1655         fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_preimage: PaymentPreimage) {
1656                 match source {
1657                         HTLCSource::OutboundRoute { .. } => {
1658                                 mem::drop(channel_state_lock);
1659                                 let mut pending_events = self.pending_events.lock().unwrap();
1660                                 pending_events.push(events::Event::PaymentSent {
1661                                         payment_preimage
1662                                 });
1663                         },
1664                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, .. }) => {
1665                                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1666                                 let channel_state = channel_state_lock.borrow_parts();
1667
1668                                 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1669                                         Some(chan_id) => chan_id.clone(),
1670                                         None => {
1671                                                 // TODO: There is probably a channel manager somewhere that needs to
1672                                                 // learn the preimage as the channel already hit the chain and that's
1673                                                 // why its missing.
1674                                                 return
1675                                         }
1676                                 };
1677
1678                                 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1679                                 match chan.get_update_fulfill_htlc_and_commit(htlc_id, payment_preimage) {
1680                                         Ok((msgs, monitor_option)) => {
1681                                                 if let Some(chan_monitor) = monitor_option {
1682                                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1683                                                                 unimplemented!();// but def dont push the event...
1684                                                         }
1685                                                 }
1686                                                 if let Some((msg, commitment_signed)) = msgs {
1687                                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1688                                                                 node_id: chan.get_their_node_id(),
1689                                                                 updates: msgs::CommitmentUpdate {
1690                                                                         update_add_htlcs: Vec::new(),
1691                                                                         update_fulfill_htlcs: vec![msg],
1692                                                                         update_fail_htlcs: Vec::new(),
1693                                                                         update_fail_malformed_htlcs: Vec::new(),
1694                                                                         update_fee: None,
1695                                                                         commitment_signed,
1696                                                                 }
1697                                                         });
1698                                                 }
1699                                         },
1700                                         Err(_e) => {
1701                                                 // TODO: There is probably a channel manager somewhere that needs to
1702                                                 // learn the preimage as the channel may be about to hit the chain.
1703                                                 //TODO: Do something with e?
1704                                                 return
1705                                         },
1706                                 }
1707                         },
1708                 }
1709         }
1710
1711         /// Gets the node_id held by this ChannelManager
1712         pub fn get_our_node_id(&self) -> PublicKey {
1713                 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
1714         }
1715
1716         /// Used to restore channels to normal operation after a
1717         /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
1718         /// operation.
1719         pub fn test_restore_channel_monitor(&self) {
1720                 let mut close_results = Vec::new();
1721                 let mut htlc_forwards = Vec::new();
1722                 let mut htlc_failures = Vec::new();
1723                 let _ = self.total_consistency_lock.read().unwrap();
1724
1725                 {
1726                         let mut channel_lock = self.channel_state.lock().unwrap();
1727                         let channel_state = channel_lock.borrow_parts();
1728                         let short_to_id = channel_state.short_to_id;
1729                         let pending_msg_events = channel_state.pending_msg_events;
1730                         channel_state.by_id.retain(|_, channel| {
1731                                 if channel.is_awaiting_monitor_update() {
1732                                         let chan_monitor = channel.channel_monitor();
1733                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1734                                                 match e {
1735                                                         ChannelMonitorUpdateErr::PermanentFailure => {
1736                                                                 // TODO: There may be some pending HTLCs that we intended to fail
1737                                                                 // backwards when a monitor update failed. We should make sure
1738                                                                 // knowledge of those gets moved into the appropriate in-memory
1739                                                                 // ChannelMonitor and they get failed backwards once we get
1740                                                                 // on-chain confirmations.
1741                                                                 // Note I think #198 addresses this, so once its merged a test
1742                                                                 // should be written.
1743                                                                 if let Some(short_id) = channel.get_short_channel_id() {
1744                                                                         short_to_id.remove(&short_id);
1745                                                                 }
1746                                                                 close_results.push(channel.force_shutdown());
1747                                                                 if let Ok(update) = self.get_channel_update(&channel) {
1748                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1749                                                                                 msg: update
1750                                                                         });
1751                                                                 }
1752                                                                 false
1753                                                         },
1754                                                         ChannelMonitorUpdateErr::TemporaryFailure => true,
1755                                                 }
1756                                         } else {
1757                                                 let (raa, commitment_update, order, pending_forwards, mut pending_failures) = channel.monitor_updating_restored();
1758                                                 if !pending_forwards.is_empty() {
1759                                                         htlc_forwards.push((channel.get_short_channel_id().expect("We can't have pending forwards before funding confirmation"), pending_forwards));
1760                                                 }
1761                                                 htlc_failures.append(&mut pending_failures);
1762
1763                                                 macro_rules! handle_cs { () => {
1764                                                         if let Some(update) = commitment_update {
1765                                                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1766                                                                         node_id: channel.get_their_node_id(),
1767                                                                         updates: update,
1768                                                                 });
1769                                                         }
1770                                                 } }
1771                                                 macro_rules! handle_raa { () => {
1772                                                         if let Some(revoke_and_ack) = raa {
1773                                                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
1774                                                                         node_id: channel.get_their_node_id(),
1775                                                                         msg: revoke_and_ack,
1776                                                                 });
1777                                                         }
1778                                                 } }
1779                                                 match order {
1780                                                         RAACommitmentOrder::CommitmentFirst => {
1781                                                                 handle_cs!();
1782                                                                 handle_raa!();
1783                                                         },
1784                                                         RAACommitmentOrder::RevokeAndACKFirst => {
1785                                                                 handle_raa!();
1786                                                                 handle_cs!();
1787                                                         },
1788                                                 }
1789                                                 true
1790                                         }
1791                                 } else { true }
1792                         });
1793                 }
1794
1795                 for failure in htlc_failures.drain(..) {
1796                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
1797                 }
1798                 self.forward_htlcs(&mut htlc_forwards[..]);
1799
1800                 for res in close_results.drain(..) {
1801                         self.finish_force_close_channel(res);
1802                 }
1803         }
1804
1805         fn internal_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
1806                 if msg.chain_hash != self.genesis_hash {
1807                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash", msg.temporary_channel_id.clone()));
1808                 }
1809
1810                 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)
1811                         .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
1812                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1813                 let channel_state = channel_state_lock.borrow_parts();
1814                 match channel_state.by_id.entry(channel.channel_id()) {
1815                         hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!", msg.temporary_channel_id.clone())),
1816                         hash_map::Entry::Vacant(entry) => {
1817                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
1818                                         node_id: their_node_id.clone(),
1819                                         msg: channel.get_accept_channel(),
1820                                 });
1821                                 entry.insert(channel);
1822                         }
1823                 }
1824                 Ok(())
1825         }
1826
1827         fn internal_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
1828                 let (value, output_script, user_id) = {
1829                         let mut channel_lock = self.channel_state.lock().unwrap();
1830                         let channel_state = channel_lock.borrow_parts();
1831                         match channel_state.by_id.entry(msg.temporary_channel_id) {
1832                                 hash_map::Entry::Occupied(mut chan) => {
1833                                         if chan.get().get_their_node_id() != *their_node_id {
1834                                                 //TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
1835                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1836                                         }
1837                                         try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration), channel_state, chan);
1838                                         (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
1839                                 },
1840                                 //TODO: same as above
1841                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1842                         }
1843                 };
1844                 let mut pending_events = self.pending_events.lock().unwrap();
1845                 pending_events.push(events::Event::FundingGenerationReady {
1846                         temporary_channel_id: msg.temporary_channel_id,
1847                         channel_value_satoshis: value,
1848                         output_script: output_script,
1849                         user_channel_id: user_id,
1850                 });
1851                 Ok(())
1852         }
1853
1854         fn internal_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
1855                 let ((funding_msg, monitor_update), chan) = {
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.clone()) {
1859                                 hash_map::Entry::Occupied(mut chan) => {
1860                                         if chan.get().get_their_node_id() != *their_node_id {
1861                                                 //TODO: here and below MsgHandleErrInternal, #153 case
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().funding_created(msg), channel_state, chan), chan.remove())
1865                                 },
1866                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1867                         }
1868                 };
1869                 // Because we have exclusive ownership of the channel here we can release the channel_state
1870                 // lock before add_update_monitor
1871                 if let Err(_e) = self.monitor.add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) {
1872                         unimplemented!();
1873                 }
1874                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1875                 let channel_state = channel_state_lock.borrow_parts();
1876                 match channel_state.by_id.entry(funding_msg.channel_id) {
1877                         hash_map::Entry::Occupied(_) => {
1878                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id", funding_msg.channel_id))
1879                         },
1880                         hash_map::Entry::Vacant(e) => {
1881                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
1882                                         node_id: their_node_id.clone(),
1883                                         msg: funding_msg,
1884                                 });
1885                                 e.insert(chan);
1886                         }
1887                 }
1888                 Ok(())
1889         }
1890
1891         fn internal_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
1892                 let (funding_txo, user_id) = {
1893                         let mut channel_lock = self.channel_state.lock().unwrap();
1894                         let channel_state = channel_lock.borrow_parts();
1895                         match channel_state.by_id.entry(msg.channel_id) {
1896                                 hash_map::Entry::Occupied(mut chan) => {
1897                                         if chan.get().get_their_node_id() != *their_node_id {
1898                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1899                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1900                                         }
1901                                         let chan_monitor = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
1902                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1903                                                 unimplemented!();
1904                                         }
1905                                         (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())
1906                                 },
1907                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1908                         }
1909                 };
1910                 let mut pending_events = self.pending_events.lock().unwrap();
1911                 pending_events.push(events::Event::FundingBroadcastSafe {
1912                         funding_txo: funding_txo,
1913                         user_channel_id: user_id,
1914                 });
1915                 Ok(())
1916         }
1917
1918         fn internal_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), MsgHandleErrInternal> {
1919                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1920                 let channel_state = channel_state_lock.borrow_parts();
1921                 match channel_state.by_id.entry(msg.channel_id) {
1922                         hash_map::Entry::Occupied(mut chan) => {
1923                                 if chan.get().get_their_node_id() != *their_node_id {
1924                                         //TODO: here and below MsgHandleErrInternal, #153 case
1925                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1926                                 }
1927                                 try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
1928                                 if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
1929                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
1930                                                 node_id: their_node_id.clone(),
1931                                                 msg: announcement_sigs,
1932                                         });
1933                                 }
1934                                 Ok(())
1935                         },
1936                         hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1937                 }
1938         }
1939
1940         fn internal_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
1941                 let (mut dropped_htlcs, chan_option) = {
1942                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1943                         let channel_state = channel_state_lock.borrow_parts();
1944
1945                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1946                                 hash_map::Entry::Occupied(mut chan_entry) => {
1947                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1948                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1949                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1950                                         }
1951                                         let (shutdown, closing_signed, dropped_htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg), channel_state, chan_entry);
1952                                         if let Some(msg) = shutdown {
1953                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
1954                                                         node_id: their_node_id.clone(),
1955                                                         msg,
1956                                                 });
1957                                         }
1958                                         if let Some(msg) = closing_signed {
1959                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1960                                                         node_id: their_node_id.clone(),
1961                                                         msg,
1962                                                 });
1963                                         }
1964                                         if chan_entry.get().is_shutdown() {
1965                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1966                                                         channel_state.short_to_id.remove(&short_id);
1967                                                 }
1968                                                 (dropped_htlcs, Some(chan_entry.remove_entry().1))
1969                                         } else { (dropped_htlcs, None) }
1970                                 },
1971                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1972                         }
1973                 };
1974                 for htlc_source in dropped_htlcs.drain(..) {
1975                         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() });
1976                 }
1977                 if let Some(chan) = chan_option {
1978                         if let Ok(update) = self.get_channel_update(&chan) {
1979                                 let mut channel_state = self.channel_state.lock().unwrap();
1980                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1981                                         msg: update
1982                                 });
1983                         }
1984                 }
1985                 Ok(())
1986         }
1987
1988         fn internal_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
1989                 let (tx, chan_option) = {
1990                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1991                         let channel_state = channel_state_lock.borrow_parts();
1992                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1993                                 hash_map::Entry::Occupied(mut chan_entry) => {
1994                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1995                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1996                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1997                                         }
1998                                         let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg), channel_state, chan_entry);
1999                                         if let Some(msg) = closing_signed {
2000                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2001                                                         node_id: their_node_id.clone(),
2002                                                         msg,
2003                                                 });
2004                                         }
2005                                         if tx.is_some() {
2006                                                 // We're done with this channel, we've got a signed closing transaction and
2007                                                 // will send the closing_signed back to the remote peer upon return. This
2008                                                 // also implies there are no pending HTLCs left on the channel, so we can
2009                                                 // fully delete it from tracking (the channel monitor is still around to
2010                                                 // watch for old state broadcasts)!
2011                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2012                                                         channel_state.short_to_id.remove(&short_id);
2013                                                 }
2014                                                 (tx, Some(chan_entry.remove_entry().1))
2015                                         } else { (tx, None) }
2016                                 },
2017                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2018                         }
2019                 };
2020                 if let Some(broadcast_tx) = tx {
2021                         self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
2022                 }
2023                 if let Some(chan) = chan_option {
2024                         if let Ok(update) = self.get_channel_update(&chan) {
2025                                 let mut channel_state = self.channel_state.lock().unwrap();
2026                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2027                                         msg: update
2028                                 });
2029                         }
2030                 }
2031                 Ok(())
2032         }
2033
2034         fn internal_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
2035                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
2036                 //determine the state of the payment based on our response/if we forward anything/the time
2037                 //we take to respond. We should take care to avoid allowing such an attack.
2038                 //
2039                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
2040                 //us repeatedly garbled in different ways, and compare our error messages, which are
2041                 //encrypted with the same key. Its not immediately obvious how to usefully exploit that,
2042                 //but we should prevent it anyway.
2043
2044                 let (mut pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
2045                 let channel_state = channel_state_lock.borrow_parts();
2046
2047                 match channel_state.by_id.entry(msg.channel_id) {
2048                         hash_map::Entry::Occupied(mut chan) => {
2049                                 if chan.get().get_their_node_id() != *their_node_id {
2050                                         //TODO: here MsgHandleErrInternal, #153 case
2051                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2052                                 }
2053                                 if !chan.get().is_usable() {
2054                                         // If the update_add is completely bogus, the call will Err and we will close,
2055                                         // but if we've sent a shutdown and they haven't acknowledged it yet, we just
2056                                         // want to reject the new HTLC and fail it backwards instead of forwarding.
2057                                         if let PendingHTLCStatus::Forward(PendingForwardHTLCInfo { incoming_shared_secret, .. }) = pending_forward_info {
2058                                                 let chan_update = self.get_channel_update(chan.get());
2059                                                 pending_forward_info = PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
2060                                                         channel_id: msg.channel_id,
2061                                                         htlc_id: msg.htlc_id,
2062                                                         reason: if let Ok(update) = chan_update {
2063                                                                 // TODO: Note that |20 is defined as "channel FROM the processing
2064                                                                 // node has been disabled" (emphasis mine), which seems to imply
2065                                                                 // that we can't return |20 for an inbound channel being disabled.
2066                                                                 // This probably needs a spec update but should definitely be
2067                                                                 // allowed.
2068                                                                 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x1000|20, &{
2069                                                                         let mut res = Vec::with_capacity(8 + 128);
2070                                                                         res.extend_from_slice(&byte_utils::be16_to_array(update.contents.flags));
2071                                                                         res.extend_from_slice(&update.encode_with_len()[..]);
2072                                                                         res
2073                                                                 }[..])
2074                                                         } else {
2075                                                                 // This can only happen if the channel isn't in the fully-funded
2076                                                                 // state yet, implying our counterparty is trying to route payments
2077                                                                 // over the channel back to themselves (cause no one else should
2078                                                                 // know the short_id is a lightning channel yet). We should have no
2079                                                                 // problem just calling this unknown_next_peer
2080                                                                 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x4000|10, &[])
2081                                                         },
2082                                                 }));
2083                                         }
2084                                 }
2085                                 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info), channel_state, chan);
2086                         },
2087                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2088                 }
2089                 Ok(())
2090         }
2091
2092         fn internal_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
2093                 let mut channel_lock = self.channel_state.lock().unwrap();
2094                 let htlc_source = {
2095                         let channel_state = channel_lock.borrow_parts();
2096                         match channel_state.by_id.entry(msg.channel_id) {
2097                                 hash_map::Entry::Occupied(mut chan) => {
2098                                         if chan.get().get_their_node_id() != *their_node_id {
2099                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2100                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2101                                         }
2102                                         try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), channel_state, chan)
2103                                 },
2104                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2105                         }
2106                 };
2107                 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
2108                 Ok(())
2109         }
2110
2111         // Process failure we got back from upstream on a payment we sent. Returns update and a boolean
2112         // indicating that the payment itself failed
2113         fn process_onion_failure(&self, htlc_source: &HTLCSource, mut packet_decrypted: Vec<u8>) -> (Option<msgs::HTLCFailChannelUpdate>, bool, Option<u16>) {
2114                 if let &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } = htlc_source {
2115
2116                         let mut res = None;
2117                         let mut htlc_msat = *first_hop_htlc_msat;
2118                         let mut error_code_ret = None;
2119                         let mut next_route_hop_ix = 0;
2120                         let mut is_from_final_node = false;
2121
2122                         // Handle packed channel/node updates for passing back for the route handler
2123                         Self::construct_onion_keys_callback(&self.secp_ctx, route, session_priv, |shared_secret, _, _, route_hop| {
2124                                 next_route_hop_ix += 1;
2125                                 if res.is_some() { return; }
2126
2127                                 let amt_to_forward = htlc_msat - route_hop.fee_msat;
2128                                 htlc_msat = amt_to_forward;
2129
2130                                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret[..]);
2131
2132                                 let mut decryption_tmp = Vec::with_capacity(packet_decrypted.len());
2133                                 decryption_tmp.resize(packet_decrypted.len(), 0);
2134                                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
2135                                 chacha.process(&packet_decrypted, &mut decryption_tmp[..]);
2136                                 packet_decrypted = decryption_tmp;
2137
2138                                 is_from_final_node = route.hops.last().unwrap().pubkey == route_hop.pubkey;
2139
2140                                 if let Ok(err_packet) = msgs::DecodedOnionErrorPacket::read(&mut Cursor::new(&packet_decrypted)) {
2141                                         let um = ChannelManager::gen_um_from_shared_secret(&shared_secret[..]);
2142                                         let mut hmac = HmacEngine::<Sha256>::new(&um);
2143                                         hmac.input(&err_packet.encode()[32..]);
2144
2145                                         if crypto::util::fixed_time_eq(&Hmac::from_engine(hmac).into_inner(), &err_packet.hmac) {
2146                                                 if let Some(error_code_slice) = err_packet.failuremsg.get(0..2) {
2147                                                         const PERM: u16 = 0x4000;
2148                                                         const NODE: u16 = 0x2000;
2149                                                         const UPDATE: u16 = 0x1000;
2150
2151                                                         let error_code = byte_utils::slice_to_be16(&error_code_slice);
2152                                                         error_code_ret = Some(error_code);
2153
2154                                                         let (debug_field, debug_field_size) = errors::get_onion_debug_field(error_code);
2155
2156                                                         // indicate that payment parameter has failed and no need to
2157                                                         // update Route object
2158                                                         let payment_failed = (match error_code & 0xff {
2159                                                                 15|16|17|18|19 => true,
2160                                                                 _ => false,
2161                                                         } && is_from_final_node) // PERM bit observed below even this error is from the intermediate nodes
2162                                                         || error_code == 21; // Special case error 21 as the Route object is bogus, TODO: Maybe fail the node if the CLTV was reasonable?
2163
2164                                                         let mut fail_channel_update = None;
2165
2166                                                         if error_code & NODE == NODE {
2167                                                                 fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure { node_id: route_hop.pubkey, is_permanent: error_code & PERM == PERM });
2168                                                         }
2169                                                         else if error_code & PERM == PERM {
2170                                                                 fail_channel_update = if payment_failed {None} else {Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
2171                                                                         short_channel_id: route.hops[next_route_hop_ix - if next_route_hop_ix == route.hops.len() { 1 } else { 0 }].short_channel_id,
2172                                                                         is_permanent: true,
2173                                                                 })};
2174                                                         }
2175                                                         else if error_code & UPDATE == UPDATE {
2176                                                                 if let Some(update_len_slice) = err_packet.failuremsg.get(debug_field_size+2..debug_field_size+4) {
2177                                                                         let update_len = byte_utils::slice_to_be16(&update_len_slice) as usize;
2178                                                                         if let Some(update_slice) = err_packet.failuremsg.get(debug_field_size + 4..debug_field_size + 4 + update_len) {
2179                                                                                 if let Ok(chan_update) = msgs::ChannelUpdate::read(&mut Cursor::new(&update_slice)) {
2180                                                                                         // if channel_update should NOT have caused the failure:
2181                                                                                         // MAY treat the channel_update as invalid.
2182                                                                                         let is_chan_update_invalid = match error_code & 0xff {
2183                                                                                                 7 => false,
2184                                                                                                 11 => amt_to_forward > chan_update.contents.htlc_minimum_msat,
2185                                                                                                 12 => {
2186                                                                                                         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) });
2187                                                                                                         new_fee.is_some() && route_hop.fee_msat >= new_fee.unwrap()
2188                                                                                                 }
2189                                                                                                 13 => route_hop.cltv_expiry_delta as u16 >= chan_update.contents.cltv_expiry_delta,
2190                                                                                                 14 => false, // expiry_too_soon; always valid?
2191                                                                                                 20 => chan_update.contents.flags & 2 == 0,
2192                                                                                                 _ => false, // unknown error code; take channel_update as valid
2193                                                                                         };
2194                                                                                         fail_channel_update = if is_chan_update_invalid {
2195                                                                                                 // This probably indicates the node which forwarded
2196                                                                                                 // to the node in question corrupted something.
2197                                                                                                 Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
2198                                                                                                         short_channel_id: route_hop.short_channel_id,
2199                                                                                                         is_permanent: true,
2200                                                                                                 })
2201                                                                                         } else {
2202                                                                                                 Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {
2203                                                                                                         msg: chan_update,
2204                                                                                                 })
2205                                                                                         };
2206                                                                                 }
2207                                                                         }
2208                                                                 }
2209                                                                 if fail_channel_update.is_none() {
2210                                                                         // They provided an UPDATE which was obviously bogus, not worth
2211                                                                         // trying to relay through them anymore.
2212                                                                         fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2213                                                                                 node_id: route_hop.pubkey,
2214                                                                                 is_permanent: true,
2215                                                                         });
2216                                                                 }
2217                                                         } else if !payment_failed {
2218                                                                 // We can't understand their error messages and they failed to
2219                                                                 // forward...they probably can't understand our forwards so its
2220                                                                 // really not worth trying any further.
2221                                                                 fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2222                                                                         node_id: route_hop.pubkey,
2223                                                                         is_permanent: true,
2224                                                                 });
2225                                                         }
2226
2227                                                         // TODO: Here (and a few other places) we assume that BADONION errors
2228                                                         // are always "sourced" from the node previous to the one which failed
2229                                                         // to decode the onion.
2230                                                         res = Some((fail_channel_update, !(error_code & PERM == PERM && is_from_final_node)));
2231
2232                                                         let (description, title) = errors::get_onion_error_description(error_code);
2233                                                         if debug_field_size > 0 && err_packet.failuremsg.len() >= 4 + debug_field_size {
2234                                                                 log_warn!(self, "Onion Error[{}({:#x}) {}({})] {}", title, error_code, debug_field, log_bytes!(&err_packet.failuremsg[4..4+debug_field_size]), description);
2235                                                         }
2236                                                         else {
2237                                                                 log_warn!(self, "Onion Error[{}({:#x})] {}", title, error_code, description);
2238                                                         }
2239                                                 } else {
2240                                                         // Useless packet that we can't use but it passed HMAC, so it
2241                                                         // definitely came from the peer in question
2242                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2243                                                                 node_id: route_hop.pubkey,
2244                                                                 is_permanent: true,
2245                                                         }), !is_from_final_node));
2246                                                 }
2247                                         }
2248                                 }
2249                         }).expect("Route that we sent via spontaneously grew invalid keys in the middle of it?");
2250                         if let Some((channel_update, payment_retryable)) = res {
2251                                 (channel_update, payment_retryable, error_code_ret)
2252                         } else {
2253                                 // only not set either packet unparseable or hmac does not match with any
2254                                 // payment not retryable only when garbage is from the final node
2255                                 (None, !is_from_final_node, None)
2256                         }
2257                 } else { unreachable!(); }
2258         }
2259
2260         fn internal_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
2261                 let mut channel_lock = self.channel_state.lock().unwrap();
2262                 let channel_state = channel_lock.borrow_parts();
2263                 match channel_state.by_id.entry(msg.channel_id) {
2264                         hash_map::Entry::Occupied(mut chan) => {
2265                                 if chan.get().get_their_node_id() != *their_node_id {
2266                                         //TODO: here and below MsgHandleErrInternal, #153 case
2267                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2268                                 }
2269                                 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::ErrorPacket { err: msg.reason.clone() }), channel_state, chan);
2270                         },
2271                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2272                 }
2273                 Ok(())
2274         }
2275
2276         fn internal_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
2277                 let mut channel_lock = self.channel_state.lock().unwrap();
2278                 let channel_state = channel_lock.borrow_parts();
2279                 match channel_state.by_id.entry(msg.channel_id) {
2280                         hash_map::Entry::Occupied(mut chan) => {
2281                                 if chan.get().get_their_node_id() != *their_node_id {
2282                                         //TODO: here and below MsgHandleErrInternal, #153 case
2283                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2284                                 }
2285                                 if (msg.failure_code & 0x8000) == 0 {
2286                                         try_chan_entry!(self, Err(ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set")), channel_state, chan);
2287                                 }
2288                                 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);
2289                                 Ok(())
2290                         },
2291                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2292                 }
2293         }
2294
2295         fn internal_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
2296                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2297                 let channel_state = channel_state_lock.borrow_parts();
2298                 match channel_state.by_id.entry(msg.channel_id) {
2299                         hash_map::Entry::Occupied(mut chan) => {
2300                                 if chan.get().get_their_node_id() != *their_node_id {
2301                                         //TODO: here and below MsgHandleErrInternal, #153 case
2302                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2303                                 }
2304                                 let (revoke_and_ack, commitment_signed, closing_signed, chan_monitor) =
2305                                         try_chan_entry!(self, chan.get_mut().commitment_signed(&msg, &*self.fee_estimator), channel_state, chan);
2306                                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2307                                         return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, commitment_signed.is_some());
2308                                         //TODO: Rebroadcast closing_signed if present on monitor update restoration
2309                                 }
2310                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2311                                         node_id: their_node_id.clone(),
2312                                         msg: revoke_and_ack,
2313                                 });
2314                                 if let Some(msg) = commitment_signed {
2315                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2316                                                 node_id: their_node_id.clone(),
2317                                                 updates: msgs::CommitmentUpdate {
2318                                                         update_add_htlcs: Vec::new(),
2319                                                         update_fulfill_htlcs: Vec::new(),
2320                                                         update_fail_htlcs: Vec::new(),
2321                                                         update_fail_malformed_htlcs: Vec::new(),
2322                                                         update_fee: None,
2323                                                         commitment_signed: msg,
2324                                                 },
2325                                         });
2326                                 }
2327                                 if let Some(msg) = closing_signed {
2328                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2329                                                 node_id: their_node_id.clone(),
2330                                                 msg,
2331                                         });
2332                                 }
2333                                 Ok(())
2334                         },
2335                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2336                 }
2337         }
2338
2339         #[inline]
2340         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64)>)]) {
2341                 for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
2342                         let mut forward_event = None;
2343                         if !pending_forwards.is_empty() {
2344                                 let mut channel_state = self.channel_state.lock().unwrap();
2345                                 if channel_state.forward_htlcs.is_empty() {
2346                                         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));
2347                                         channel_state.next_forward = forward_event.unwrap();
2348                                 }
2349                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2350                                         match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
2351                                                 hash_map::Entry::Occupied(mut entry) => {
2352                                                         entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info });
2353                                                 },
2354                                                 hash_map::Entry::Vacant(entry) => {
2355                                                         entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info }));
2356                                                 }
2357                                         }
2358                                 }
2359                         }
2360                         match forward_event {
2361                                 Some(time) => {
2362                                         let mut pending_events = self.pending_events.lock().unwrap();
2363                                         pending_events.push(events::Event::PendingHTLCsForwardable {
2364                                                 time_forwardable: time
2365                                         });
2366                                 }
2367                                 None => {},
2368                         }
2369                 }
2370         }
2371
2372         fn internal_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
2373                 let (pending_forwards, mut pending_failures, short_channel_id) = {
2374                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2375                         let channel_state = channel_state_lock.borrow_parts();
2376                         match channel_state.by_id.entry(msg.channel_id) {
2377                                 hash_map::Entry::Occupied(mut chan) => {
2378                                         if chan.get().get_their_node_id() != *their_node_id {
2379                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2380                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2381                                         }
2382                                         let (commitment_update, pending_forwards, pending_failures, closing_signed, chan_monitor) =
2383                                                 try_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &*self.fee_estimator), channel_state, chan);
2384                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2385                                                 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, pending_forwards, pending_failures);
2386                                         }
2387                                         if let Some(updates) = commitment_update {
2388                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2389                                                         node_id: their_node_id.clone(),
2390                                                         updates,
2391                                                 });
2392                                         }
2393                                         if let Some(msg) = closing_signed {
2394                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2395                                                         node_id: their_node_id.clone(),
2396                                                         msg,
2397                                                 });
2398                                         }
2399                                         (pending_forwards, pending_failures, chan.get().get_short_channel_id().expect("RAA should only work on a short-id-available channel"))
2400                                 },
2401                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2402                         }
2403                 };
2404                 for failure in pending_failures.drain(..) {
2405                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2406                 }
2407                 self.forward_htlcs(&mut [(short_channel_id, pending_forwards)]);
2408
2409                 Ok(())
2410         }
2411
2412         fn internal_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2413                 let mut channel_lock = self.channel_state.lock().unwrap();
2414                 let channel_state = channel_lock.borrow_parts();
2415                 match channel_state.by_id.entry(msg.channel_id) {
2416                         hash_map::Entry::Occupied(mut chan) => {
2417                                 if chan.get().get_their_node_id() != *their_node_id {
2418                                         //TODO: here and below MsgHandleErrInternal, #153 case
2419                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2420                                 }
2421                                 try_chan_entry!(self, chan.get_mut().update_fee(&*self.fee_estimator, &msg), channel_state, chan);
2422                         },
2423                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2424                 }
2425                 Ok(())
2426         }
2427
2428         fn internal_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2429                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2430                 let channel_state = channel_state_lock.borrow_parts();
2431
2432                 match channel_state.by_id.entry(msg.channel_id) {
2433                         hash_map::Entry::Occupied(mut chan) => {
2434                                 if chan.get().get_their_node_id() != *their_node_id {
2435                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2436                                 }
2437                                 if !chan.get().is_usable() {
2438                                         return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Got an announcement_signatures before we were ready for it", action: Some(msgs::ErrorAction::IgnoreError)}));
2439                                 }
2440
2441                                 let our_node_id = self.get_our_node_id();
2442                                 let (announcement, our_bitcoin_sig) =
2443                                         try_chan_entry!(self, chan.get_mut().get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone()), channel_state, chan);
2444
2445                                 let were_node_one = announcement.node_id_1 == our_node_id;
2446                                 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
2447                                 if self.secp_ctx.verify(&msghash, &msg.node_signature, if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 }).is_err() ||
2448                                                 self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 }).is_err() {
2449                                         try_chan_entry!(self, Err(ChannelError::Close("Bad announcement_signatures node_signature")), channel_state, chan);
2450                                 }
2451
2452                                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2453
2454                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
2455                                         msg: msgs::ChannelAnnouncement {
2456                                                 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
2457                                                 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
2458                                                 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
2459                                                 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
2460                                                 contents: announcement,
2461                                         },
2462                                         update_msg: self.get_channel_update(chan.get()).unwrap(), // can only fail if we're not in a ready state
2463                                 });
2464                         },
2465                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2466                 }
2467                 Ok(())
2468         }
2469
2470         fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
2471                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2472                 let channel_state = channel_state_lock.borrow_parts();
2473
2474                 match channel_state.by_id.entry(msg.channel_id) {
2475                         hash_map::Entry::Occupied(mut chan) => {
2476                                 if chan.get().get_their_node_id() != *their_node_id {
2477                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2478                                 }
2479                                 let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, mut order, shutdown) =
2480                                         try_chan_entry!(self, chan.get_mut().channel_reestablish(msg), channel_state, chan);
2481                                 if let Some(monitor) = channel_monitor {
2482                                         if let Err(e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
2483                                                 // channel_reestablish doesn't guarantee the order it returns is sensical
2484                                                 // for the messages it returns, but if we're setting what messages to
2485                                                 // re-transmit on monitor update success, we need to make sure it is sane.
2486                                                 if revoke_and_ack.is_none() {
2487                                                         order = RAACommitmentOrder::CommitmentFirst;
2488                                                 }
2489                                                 if commitment_update.is_none() {
2490                                                         order = RAACommitmentOrder::RevokeAndACKFirst;
2491                                                 }
2492                                                 return_monitor_err!(self, e, channel_state, chan, order);
2493                                                 //TODO: Resend the funding_locked if needed once we get the monitor running again
2494                                         }
2495                                 }
2496                                 if let Some(msg) = funding_locked {
2497                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2498                                                 node_id: their_node_id.clone(),
2499                                                 msg
2500                                         });
2501                                 }
2502                                 macro_rules! send_raa { () => {
2503                                         if let Some(msg) = revoke_and_ack {
2504                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2505                                                         node_id: their_node_id.clone(),
2506                                                         msg
2507                                                 });
2508                                         }
2509                                 } }
2510                                 macro_rules! send_cu { () => {
2511                                         if let Some(updates) = commitment_update {
2512                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2513                                                         node_id: their_node_id.clone(),
2514                                                         updates
2515                                                 });
2516                                         }
2517                                 } }
2518                                 match order {
2519                                         RAACommitmentOrder::RevokeAndACKFirst => {
2520                                                 send_raa!();
2521                                                 send_cu!();
2522                                         },
2523                                         RAACommitmentOrder::CommitmentFirst => {
2524                                                 send_cu!();
2525                                                 send_raa!();
2526                                         },
2527                                 }
2528                                 if let Some(msg) = shutdown {
2529                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2530                                                 node_id: their_node_id.clone(),
2531                                                 msg,
2532                                         });
2533                                 }
2534                                 Ok(())
2535                         },
2536                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2537                 }
2538         }
2539
2540         /// Begin Update fee process. Allowed only on an outbound channel.
2541         /// If successful, will generate a UpdateHTLCs event, so you should probably poll
2542         /// PeerManager::process_events afterwards.
2543         /// Note: This API is likely to change!
2544         #[doc(hidden)]
2545         pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u64) -> Result<(), APIError> {
2546                 let _ = self.total_consistency_lock.read().unwrap();
2547                 let their_node_id;
2548                 let err: Result<(), _> = loop {
2549                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2550                         let channel_state = channel_state_lock.borrow_parts();
2551
2552                         match channel_state.by_id.entry(channel_id) {
2553                                 hash_map::Entry::Vacant(_) => return Err(APIError::APIMisuseError{err: "Failed to find corresponding channel"}),
2554                                 hash_map::Entry::Occupied(mut chan) => {
2555                                         if !chan.get().is_outbound() {
2556                                                 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel"});
2557                                         }
2558                                         if chan.get().is_awaiting_monitor_update() {
2559                                                 return Err(APIError::MonitorUpdateFailed);
2560                                         }
2561                                         if !chan.get().is_live() {
2562                                                 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected"});
2563                                         }
2564                                         their_node_id = chan.get().get_their_node_id();
2565                                         if let Some((update_fee, commitment_signed, chan_monitor)) =
2566                                                         break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw), channel_state, chan)
2567                                         {
2568                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2569                                                         unimplemented!();
2570                                                 }
2571                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2572                                                         node_id: chan.get().get_their_node_id(),
2573                                                         updates: msgs::CommitmentUpdate {
2574                                                                 update_add_htlcs: Vec::new(),
2575                                                                 update_fulfill_htlcs: Vec::new(),
2576                                                                 update_fail_htlcs: Vec::new(),
2577                                                                 update_fail_malformed_htlcs: Vec::new(),
2578                                                                 update_fee: Some(update_fee),
2579                                                                 commitment_signed,
2580                                                         },
2581                                                 });
2582                                         }
2583                                 },
2584                         }
2585                         return Ok(())
2586                 };
2587
2588                 match handle_error!(self, err, their_node_id) {
2589                         Ok(_) => unreachable!(),
2590                         Err(e) => {
2591                                 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
2592                                 } else {
2593                                         log_error!(self, "Got bad keys: {}!", e.err);
2594                                         let mut channel_state = self.channel_state.lock().unwrap();
2595                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
2596                                                 node_id: their_node_id,
2597                                                 action: e.action,
2598                                         });
2599                                 }
2600                                 Err(APIError::APIMisuseError { err: e.err })
2601                         },
2602                 }
2603         }
2604 }
2605
2606 impl events::MessageSendEventsProvider for ChannelManager {
2607         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
2608                 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2609                 // user to serialize a ChannelManager with pending events in it and lose those events on
2610                 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2611                 {
2612                         //TODO: This behavior should be documented.
2613                         for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2614                                 if let Some(preimage) = htlc_update.payment_preimage {
2615                                         log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2616                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2617                                 } else {
2618                                         log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2619                                         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() });
2620                                 }
2621                         }
2622                 }
2623
2624                 let mut ret = Vec::new();
2625                 let mut channel_state = self.channel_state.lock().unwrap();
2626                 mem::swap(&mut ret, &mut channel_state.pending_msg_events);
2627                 ret
2628         }
2629 }
2630
2631 impl events::EventsProvider for ChannelManager {
2632         fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
2633                 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2634                 // user to serialize a ChannelManager with pending events in it and lose those events on
2635                 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2636                 {
2637                         //TODO: This behavior should be documented.
2638                         for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2639                                 if let Some(preimage) = htlc_update.payment_preimage {
2640                                         log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2641                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2642                                 } else {
2643                                         log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2644                                         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() });
2645                                 }
2646                         }
2647                 }
2648
2649                 let mut ret = Vec::new();
2650                 let mut pending_events = self.pending_events.lock().unwrap();
2651                 mem::swap(&mut ret, &mut *pending_events);
2652                 ret
2653         }
2654 }
2655
2656 impl ChainListener for ChannelManager {
2657         fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
2658                 let header_hash = header.bitcoin_hash();
2659                 log_trace!(self, "Block {} at height {} connected with {} txn matched", header_hash, height, txn_matched.len());
2660                 let _ = self.total_consistency_lock.read().unwrap();
2661                 let mut failed_channels = Vec::new();
2662                 {
2663                         let mut channel_lock = self.channel_state.lock().unwrap();
2664                         let channel_state = channel_lock.borrow_parts();
2665                         let short_to_id = channel_state.short_to_id;
2666                         let pending_msg_events = channel_state.pending_msg_events;
2667                         channel_state.by_id.retain(|_, channel| {
2668                                 let chan_res = channel.block_connected(header, height, txn_matched, indexes_of_txn_matched);
2669                                 if let Ok(Some(funding_locked)) = chan_res {
2670                                         pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2671                                                 node_id: channel.get_their_node_id(),
2672                                                 msg: funding_locked,
2673                                         });
2674                                         if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
2675                                                 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2676                                                         node_id: channel.get_their_node_id(),
2677                                                         msg: announcement_sigs,
2678                                                 });
2679                                         }
2680                                         short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
2681                                 } else if let Err(e) = chan_res {
2682                                         pending_msg_events.push(events::MessageSendEvent::HandleError {
2683                                                 node_id: channel.get_their_node_id(),
2684                                                 action: Some(msgs::ErrorAction::SendErrorMessage { msg: e }),
2685                                         });
2686                                         return false;
2687                                 }
2688                                 if let Some(funding_txo) = channel.get_funding_txo() {
2689                                         for tx in txn_matched {
2690                                                 for inp in tx.input.iter() {
2691                                                         if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
2692                                                                 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()));
2693                                                                 if let Some(short_id) = channel.get_short_channel_id() {
2694                                                                         short_to_id.remove(&short_id);
2695                                                                 }
2696                                                                 // It looks like our counterparty went on-chain. We go ahead and
2697                                                                 // broadcast our latest local state as well here, just in case its
2698                                                                 // some kind of SPV attack, though we expect these to be dropped.
2699                                                                 failed_channels.push(channel.force_shutdown());
2700                                                                 if let Ok(update) = self.get_channel_update(&channel) {
2701                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2702                                                                                 msg: update
2703                                                                         });
2704                                                                 }
2705                                                                 return false;
2706                                                         }
2707                                                 }
2708                                         }
2709                                 }
2710                                 if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height) {
2711                                         if let Some(short_id) = channel.get_short_channel_id() {
2712                                                 short_to_id.remove(&short_id);
2713                                         }
2714                                         failed_channels.push(channel.force_shutdown());
2715                                         // If would_broadcast_at_height() is true, the channel_monitor will broadcast
2716                                         // the latest local tx for us, so we should skip that here (it doesn't really
2717                                         // hurt anything, but does make tests a bit simpler).
2718                                         failed_channels.last_mut().unwrap().0 = Vec::new();
2719                                         if let Ok(update) = self.get_channel_update(&channel) {
2720                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2721                                                         msg: update
2722                                                 });
2723                                         }
2724                                         return false;
2725                                 }
2726                                 true
2727                         });
2728                 }
2729                 for failure in failed_channels.drain(..) {
2730                         self.finish_force_close_channel(failure);
2731                 }
2732                 self.latest_block_height.store(height as usize, Ordering::Release);
2733                 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header_hash;
2734         }
2735
2736         /// We force-close the channel without letting our counterparty participate in the shutdown
2737         fn block_disconnected(&self, header: &BlockHeader) {
2738                 let _ = self.total_consistency_lock.read().unwrap();
2739                 let mut failed_channels = Vec::new();
2740                 {
2741                         let mut channel_lock = self.channel_state.lock().unwrap();
2742                         let channel_state = channel_lock.borrow_parts();
2743                         let short_to_id = channel_state.short_to_id;
2744                         let pending_msg_events = channel_state.pending_msg_events;
2745                         channel_state.by_id.retain(|_,  v| {
2746                                 if v.block_disconnected(header) {
2747                                         if let Some(short_id) = v.get_short_channel_id() {
2748                                                 short_to_id.remove(&short_id);
2749                                         }
2750                                         failed_channels.push(v.force_shutdown());
2751                                         if let Ok(update) = self.get_channel_update(&v) {
2752                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2753                                                         msg: update
2754                                                 });
2755                                         }
2756                                         false
2757                                 } else {
2758                                         true
2759                                 }
2760                         });
2761                 }
2762                 for failure in failed_channels.drain(..) {
2763                         self.finish_force_close_channel(failure);
2764                 }
2765                 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
2766                 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
2767         }
2768 }
2769
2770 impl ChannelMessageHandler for ChannelManager {
2771         //TODO: Handle errors and close channel (or so)
2772         fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), HandleError> {
2773                 let _ = self.total_consistency_lock.read().unwrap();
2774                 handle_error!(self, self.internal_open_channel(their_node_id, msg), their_node_id)
2775         }
2776
2777         fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), HandleError> {
2778                 let _ = self.total_consistency_lock.read().unwrap();
2779                 handle_error!(self, self.internal_accept_channel(their_node_id, msg), their_node_id)
2780         }
2781
2782         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), HandleError> {
2783                 let _ = self.total_consistency_lock.read().unwrap();
2784                 handle_error!(self, self.internal_funding_created(their_node_id, msg), their_node_id)
2785         }
2786
2787         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), HandleError> {
2788                 let _ = self.total_consistency_lock.read().unwrap();
2789                 handle_error!(self, self.internal_funding_signed(their_node_id, msg), their_node_id)
2790         }
2791
2792         fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), HandleError> {
2793                 let _ = self.total_consistency_lock.read().unwrap();
2794                 handle_error!(self, self.internal_funding_locked(their_node_id, msg), their_node_id)
2795         }
2796
2797         fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), HandleError> {
2798                 let _ = self.total_consistency_lock.read().unwrap();
2799                 handle_error!(self, self.internal_shutdown(their_node_id, msg), their_node_id)
2800         }
2801
2802         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), HandleError> {
2803                 let _ = self.total_consistency_lock.read().unwrap();
2804                 handle_error!(self, self.internal_closing_signed(their_node_id, msg), their_node_id)
2805         }
2806
2807         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), msgs::HandleError> {
2808                 let _ = self.total_consistency_lock.read().unwrap();
2809                 handle_error!(self, self.internal_update_add_htlc(their_node_id, msg), their_node_id)
2810         }
2811
2812         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), HandleError> {
2813                 let _ = self.total_consistency_lock.read().unwrap();
2814                 handle_error!(self, self.internal_update_fulfill_htlc(their_node_id, msg), their_node_id)
2815         }
2816
2817         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), HandleError> {
2818                 let _ = self.total_consistency_lock.read().unwrap();
2819                 handle_error!(self, self.internal_update_fail_htlc(their_node_id, msg), their_node_id)
2820         }
2821
2822         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), HandleError> {
2823                 let _ = self.total_consistency_lock.read().unwrap();
2824                 handle_error!(self, self.internal_update_fail_malformed_htlc(their_node_id, msg), their_node_id)
2825         }
2826
2827         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), HandleError> {
2828                 let _ = self.total_consistency_lock.read().unwrap();
2829                 handle_error!(self, self.internal_commitment_signed(their_node_id, msg), their_node_id)
2830         }
2831
2832         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), HandleError> {
2833                 let _ = self.total_consistency_lock.read().unwrap();
2834                 handle_error!(self, self.internal_revoke_and_ack(their_node_id, msg), their_node_id)
2835         }
2836
2837         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), HandleError> {
2838                 let _ = self.total_consistency_lock.read().unwrap();
2839                 handle_error!(self, self.internal_update_fee(their_node_id, msg), their_node_id)
2840         }
2841
2842         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), HandleError> {
2843                 let _ = self.total_consistency_lock.read().unwrap();
2844                 handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
2845         }
2846
2847         fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), HandleError> {
2848                 let _ = self.total_consistency_lock.read().unwrap();
2849                 handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), their_node_id)
2850         }
2851
2852         fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
2853                 let _ = self.total_consistency_lock.read().unwrap();
2854                 let mut failed_channels = Vec::new();
2855                 let mut failed_payments = Vec::new();
2856                 {
2857                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2858                         let channel_state = channel_state_lock.borrow_parts();
2859                         let short_to_id = channel_state.short_to_id;
2860                         let pending_msg_events = channel_state.pending_msg_events;
2861                         if no_connection_possible {
2862                                 log_debug!(self, "Failing all channels with {} due to no_connection_possible", log_pubkey!(their_node_id));
2863                                 channel_state.by_id.retain(|_, chan| {
2864                                         if chan.get_their_node_id() == *their_node_id {
2865                                                 if let Some(short_id) = chan.get_short_channel_id() {
2866                                                         short_to_id.remove(&short_id);
2867                                                 }
2868                                                 failed_channels.push(chan.force_shutdown());
2869                                                 if let Ok(update) = self.get_channel_update(&chan) {
2870                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2871                                                                 msg: update
2872                                                         });
2873                                                 }
2874                                                 false
2875                                         } else {
2876                                                 true
2877                                         }
2878                                 });
2879                         } else {
2880                                 log_debug!(self, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(their_node_id));
2881                                 channel_state.by_id.retain(|_, chan| {
2882                                         if chan.get_their_node_id() == *their_node_id {
2883                                                 //TODO: mark channel disabled (and maybe announce such after a timeout).
2884                                                 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused();
2885                                                 if !failed_adds.is_empty() {
2886                                                         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
2887                                                         failed_payments.push((chan_update, failed_adds));
2888                                                 }
2889                                                 if chan.is_shutdown() {
2890                                                         if let Some(short_id) = chan.get_short_channel_id() {
2891                                                                 short_to_id.remove(&short_id);
2892                                                         }
2893                                                         return false;
2894                                                 }
2895                                         }
2896                                         true
2897                                 })
2898                         }
2899                 }
2900                 for failure in failed_channels.drain(..) {
2901                         self.finish_force_close_channel(failure);
2902                 }
2903                 for (chan_update, mut htlc_sources) in failed_payments {
2904                         for (htlc_source, payment_hash) in htlc_sources.drain(..) {
2905                                 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
2906                         }
2907                 }
2908         }
2909
2910         fn peer_connected(&self, their_node_id: &PublicKey) {
2911                 log_debug!(self, "Generating channel_reestablish events for {}", log_pubkey!(their_node_id));
2912
2913                 let _ = self.total_consistency_lock.read().unwrap();
2914                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2915                 let channel_state = channel_state_lock.borrow_parts();
2916                 let pending_msg_events = channel_state.pending_msg_events;
2917                 channel_state.by_id.retain(|_, chan| {
2918                         if chan.get_their_node_id() == *their_node_id {
2919                                 if !chan.have_received_message() {
2920                                         // If we created this (outbound) channel while we were disconnected from the
2921                                         // peer we probably failed to send the open_channel message, which is now
2922                                         // lost. We can't have had anything pending related to this channel, so we just
2923                                         // drop it.
2924                                         false
2925                                 } else {
2926                                         pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
2927                                                 node_id: chan.get_their_node_id(),
2928                                                 msg: chan.get_channel_reestablish(),
2929                                         });
2930                                         true
2931                                 }
2932                         } else { true }
2933                 });
2934                 //TODO: Also re-broadcast announcement_signatures
2935         }
2936
2937         fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
2938                 let _ = self.total_consistency_lock.read().unwrap();
2939
2940                 if msg.channel_id == [0; 32] {
2941                         for chan in self.list_channels() {
2942                                 if chan.remote_network_id == *their_node_id {
2943                                         self.force_close_channel(&chan.channel_id);
2944                                 }
2945                         }
2946                 } else {
2947                         self.force_close_channel(&msg.channel_id);
2948                 }
2949         }
2950 }
2951
2952 const SERIALIZATION_VERSION: u8 = 1;
2953 const MIN_SERIALIZATION_VERSION: u8 = 1;
2954
2955 impl Writeable for PendingForwardHTLCInfo {
2956         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2957                 if let &Some(ref onion) = &self.onion_packet {
2958                         1u8.write(writer)?;
2959                         onion.write(writer)?;
2960                 } else {
2961                         0u8.write(writer)?;
2962                 }
2963                 self.incoming_shared_secret.write(writer)?;
2964                 self.payment_hash.write(writer)?;
2965                 self.short_channel_id.write(writer)?;
2966                 self.amt_to_forward.write(writer)?;
2967                 self.outgoing_cltv_value.write(writer)?;
2968                 Ok(())
2969         }
2970 }
2971
2972 impl<R: ::std::io::Read> Readable<R> for PendingForwardHTLCInfo {
2973         fn read(reader: &mut R) -> Result<PendingForwardHTLCInfo, DecodeError> {
2974                 let onion_packet = match <u8 as Readable<R>>::read(reader)? {
2975                         0 => None,
2976                         1 => Some(msgs::OnionPacket::read(reader)?),
2977                         _ => return Err(DecodeError::InvalidValue),
2978                 };
2979                 Ok(PendingForwardHTLCInfo {
2980                         onion_packet,
2981                         incoming_shared_secret: Readable::read(reader)?,
2982                         payment_hash: Readable::read(reader)?,
2983                         short_channel_id: Readable::read(reader)?,
2984                         amt_to_forward: Readable::read(reader)?,
2985                         outgoing_cltv_value: Readable::read(reader)?,
2986                 })
2987         }
2988 }
2989
2990 impl Writeable for HTLCFailureMsg {
2991         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2992                 match self {
2993                         &HTLCFailureMsg::Relay(ref fail_msg) => {
2994                                 0u8.write(writer)?;
2995                                 fail_msg.write(writer)?;
2996                         },
2997                         &HTLCFailureMsg::Malformed(ref fail_msg) => {
2998                                 1u8.write(writer)?;
2999                                 fail_msg.write(writer)?;
3000                         }
3001                 }
3002                 Ok(())
3003         }
3004 }
3005
3006 impl<R: ::std::io::Read> Readable<R> for HTLCFailureMsg {
3007         fn read(reader: &mut R) -> Result<HTLCFailureMsg, DecodeError> {
3008                 match <u8 as Readable<R>>::read(reader)? {
3009                         0 => Ok(HTLCFailureMsg::Relay(Readable::read(reader)?)),
3010                         1 => Ok(HTLCFailureMsg::Malformed(Readable::read(reader)?)),
3011                         _ => Err(DecodeError::InvalidValue),
3012                 }
3013         }
3014 }
3015
3016 impl Writeable for PendingHTLCStatus {
3017         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3018                 match self {
3019                         &PendingHTLCStatus::Forward(ref forward_info) => {
3020                                 0u8.write(writer)?;
3021                                 forward_info.write(writer)?;
3022                         },
3023                         &PendingHTLCStatus::Fail(ref fail_msg) => {
3024                                 1u8.write(writer)?;
3025                                 fail_msg.write(writer)?;
3026                         }
3027                 }
3028                 Ok(())
3029         }
3030 }
3031
3032 impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
3033         fn read(reader: &mut R) -> Result<PendingHTLCStatus, DecodeError> {
3034                 match <u8 as Readable<R>>::read(reader)? {
3035                         0 => Ok(PendingHTLCStatus::Forward(Readable::read(reader)?)),
3036                         1 => Ok(PendingHTLCStatus::Fail(Readable::read(reader)?)),
3037                         _ => Err(DecodeError::InvalidValue),
3038                 }
3039         }
3040 }
3041
3042 impl_writeable!(HTLCPreviousHopData, 0, {
3043         short_channel_id,
3044         htlc_id,
3045         incoming_packet_shared_secret
3046 });
3047
3048 impl Writeable for HTLCSource {
3049         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3050                 match self {
3051                         &HTLCSource::PreviousHopData(ref hop_data) => {
3052                                 0u8.write(writer)?;
3053                                 hop_data.write(writer)?;
3054                         },
3055                         &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } => {
3056                                 1u8.write(writer)?;
3057                                 route.write(writer)?;
3058                                 session_priv.write(writer)?;
3059                                 first_hop_htlc_msat.write(writer)?;
3060                         }
3061                 }
3062                 Ok(())
3063         }
3064 }
3065
3066 impl<R: ::std::io::Read> Readable<R> for HTLCSource {
3067         fn read(reader: &mut R) -> Result<HTLCSource, DecodeError> {
3068                 match <u8 as Readable<R>>::read(reader)? {
3069                         0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
3070                         1 => Ok(HTLCSource::OutboundRoute {
3071                                 route: Readable::read(reader)?,
3072                                 session_priv: Readable::read(reader)?,
3073                                 first_hop_htlc_msat: Readable::read(reader)?,
3074                         }),
3075                         _ => Err(DecodeError::InvalidValue),
3076                 }
3077         }
3078 }
3079
3080 impl Writeable for HTLCFailReason {
3081         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3082                 match self {
3083                         &HTLCFailReason::ErrorPacket { ref err } => {
3084                                 0u8.write(writer)?;
3085                                 err.write(writer)?;
3086                         },
3087                         &HTLCFailReason::Reason { ref failure_code, ref data } => {
3088                                 1u8.write(writer)?;
3089                                 failure_code.write(writer)?;
3090                                 data.write(writer)?;
3091                         }
3092                 }
3093                 Ok(())
3094         }
3095 }
3096
3097 impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
3098         fn read(reader: &mut R) -> Result<HTLCFailReason, DecodeError> {
3099                 match <u8 as Readable<R>>::read(reader)? {
3100                         0 => Ok(HTLCFailReason::ErrorPacket { err: Readable::read(reader)? }),
3101                         1 => Ok(HTLCFailReason::Reason {
3102                                 failure_code: Readable::read(reader)?,
3103                                 data: Readable::read(reader)?,
3104                         }),
3105                         _ => Err(DecodeError::InvalidValue),
3106                 }
3107         }
3108 }
3109
3110 impl_writeable!(HTLCForwardInfo, 0, {
3111         prev_short_channel_id,
3112         prev_htlc_id,
3113         forward_info
3114 });
3115
3116 impl Writeable for ChannelManager {
3117         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3118                 let _ = self.total_consistency_lock.write().unwrap();
3119
3120                 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
3121                 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
3122
3123                 self.genesis_hash.write(writer)?;
3124                 (self.latest_block_height.load(Ordering::Acquire) as u32).write(writer)?;
3125                 self.last_block_hash.lock().unwrap().write(writer)?;
3126
3127                 let channel_state = self.channel_state.lock().unwrap();
3128                 let mut unfunded_channels = 0;
3129                 for (_, channel) in channel_state.by_id.iter() {
3130                         if !channel.is_funding_initiated() {
3131                                 unfunded_channels += 1;
3132                         }
3133                 }
3134                 ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
3135                 for (_, channel) in channel_state.by_id.iter() {
3136                         if channel.is_funding_initiated() {
3137                                 channel.write(writer)?;
3138                         }
3139                 }
3140
3141                 (channel_state.forward_htlcs.len() as u64).write(writer)?;
3142                 for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
3143                         short_channel_id.write(writer)?;
3144                         (pending_forwards.len() as u64).write(writer)?;
3145                         for forward in pending_forwards {
3146                                 forward.write(writer)?;
3147                         }
3148                 }
3149
3150                 (channel_state.claimable_htlcs.len() as u64).write(writer)?;
3151                 for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
3152                         payment_hash.write(writer)?;
3153                         (previous_hops.len() as u64).write(writer)?;
3154                         for previous_hop in previous_hops {
3155                                 previous_hop.write(writer)?;
3156                         }
3157                 }
3158
3159                 Ok(())
3160         }
3161 }
3162
3163 /// Arguments for the creation of a ChannelManager that are not deserialized.
3164 ///
3165 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
3166 /// is:
3167 /// 1) Deserialize all stored ChannelMonitors.
3168 /// 2) Deserialize the ChannelManager by filling in this struct and calling <(Sha256dHash,
3169 ///    ChannelManager)>::read(reader, args).
3170 ///    This may result in closing some Channels if the ChannelMonitor is newer than the stored
3171 ///    ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
3172 /// 3) Register all relevant ChannelMonitor outpoints with your chain watch mechanism using
3173 ///    ChannelMonitor::get_monitored_outpoints and ChannelMonitor::get_funding_txo().
3174 /// 4) Reconnect blocks on your ChannelMonitors.
3175 /// 5) Move the ChannelMonitors into your local ManyChannelMonitor.
3176 /// 6) Disconnect/connect blocks on the ChannelManager.
3177 /// 7) Register the new ChannelManager with your ChainWatchInterface (this does not happen
3178 ///    automatically as it does in ChannelManager::new()).
3179 pub struct ChannelManagerReadArgs<'a> {
3180         /// The keys provider which will give us relevant keys. Some keys will be loaded during
3181         /// deserialization.
3182         pub keys_manager: Arc<KeysInterface>,
3183
3184         /// The fee_estimator for use in the ChannelManager in the future.
3185         ///
3186         /// No calls to the FeeEstimator will be made during deserialization.
3187         pub fee_estimator: Arc<FeeEstimator>,
3188         /// The ManyChannelMonitor for use in the ChannelManager in the future.
3189         ///
3190         /// No calls to the ManyChannelMonitor will be made during deserialization. It is assumed that
3191         /// you have deserialized ChannelMonitors separately and will add them to your
3192         /// ManyChannelMonitor after deserializing this ChannelManager.
3193         pub monitor: Arc<ManyChannelMonitor>,
3194         /// The ChainWatchInterface for use in the ChannelManager in the future.
3195         ///
3196         /// No calls to the ChainWatchInterface will be made during deserialization.
3197         pub chain_monitor: Arc<ChainWatchInterface>,
3198         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
3199         /// used to broadcast the latest local commitment transactions of channels which must be
3200         /// force-closed during deserialization.
3201         pub tx_broadcaster: Arc<BroadcasterInterface>,
3202         /// The Logger for use in the ChannelManager and which may be used to log information during
3203         /// deserialization.
3204         pub logger: Arc<Logger>,
3205         /// Default settings used for new channels. Any existing channels will continue to use the
3206         /// runtime settings which were stored when the ChannelManager was serialized.
3207         pub default_config: UserConfig,
3208
3209         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
3210         /// value.get_funding_txo() should be the key).
3211         ///
3212         /// If a monitor is inconsistent with the channel state during deserialization the channel will
3213         /// be force-closed using the data in the channelmonitor and the Channel will be dropped. This
3214         /// is true for missing channels as well. If there is a monitor missing for which we find
3215         /// channel data Err(DecodeError::InvalidValue) will be returned.
3216         ///
3217         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
3218         /// this struct.
3219         pub channel_monitors: &'a HashMap<OutPoint, &'a ChannelMonitor>,
3220 }
3221
3222 impl<'a, R : ::std::io::Read> ReadableArgs<R, ChannelManagerReadArgs<'a>> for (Sha256dHash, ChannelManager) {
3223         fn read(reader: &mut R, args: ChannelManagerReadArgs<'a>) -> Result<Self, DecodeError> {
3224                 let _ver: u8 = Readable::read(reader)?;
3225                 let min_ver: u8 = Readable::read(reader)?;
3226                 if min_ver > SERIALIZATION_VERSION {
3227                         return Err(DecodeError::UnknownVersion);
3228                 }
3229
3230                 let genesis_hash: Sha256dHash = Readable::read(reader)?;
3231                 let latest_block_height: u32 = Readable::read(reader)?;
3232                 let last_block_hash: Sha256dHash = Readable::read(reader)?;
3233
3234                 let mut closed_channels = Vec::new();
3235
3236                 let channel_count: u64 = Readable::read(reader)?;
3237                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
3238                 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3239                 let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3240                 for _ in 0..channel_count {
3241                         let mut channel: Channel = ReadableArgs::read(reader, args.logger.clone())?;
3242                         if channel.last_block_connected != last_block_hash {
3243                                 return Err(DecodeError::InvalidValue);
3244                         }
3245
3246                         let funding_txo = channel.channel_monitor().get_funding_txo().ok_or(DecodeError::InvalidValue)?;
3247                         funding_txo_set.insert(funding_txo.clone());
3248                         if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
3249                                 if channel.get_cur_local_commitment_transaction_number() != monitor.get_cur_local_commitment_number() ||
3250                                                 channel.get_revoked_remote_commitment_transaction_number() != monitor.get_min_seen_secret() ||
3251                                                 channel.get_cur_remote_commitment_transaction_number() != monitor.get_cur_remote_commitment_number() {
3252                                         let mut force_close_res = channel.force_shutdown();
3253                                         force_close_res.0 = monitor.get_latest_local_commitment_txn();
3254                                         closed_channels.push(force_close_res);
3255                                 } else {
3256                                         if let Some(short_channel_id) = channel.get_short_channel_id() {
3257                                                 short_to_id.insert(short_channel_id, channel.channel_id());
3258                                         }
3259                                         by_id.insert(channel.channel_id(), channel);
3260                                 }
3261                         } else {
3262                                 return Err(DecodeError::InvalidValue);
3263                         }
3264                 }
3265
3266                 for (ref funding_txo, ref monitor) in args.channel_monitors.iter() {
3267                         if !funding_txo_set.contains(funding_txo) {
3268                                 closed_channels.push((monitor.get_latest_local_commitment_txn(), Vec::new()));
3269                         }
3270                 }
3271
3272                 let forward_htlcs_count: u64 = Readable::read(reader)?;
3273                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
3274                 for _ in 0..forward_htlcs_count {
3275                         let short_channel_id = Readable::read(reader)?;
3276                         let pending_forwards_count: u64 = Readable::read(reader)?;
3277                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, 128));
3278                         for _ in 0..pending_forwards_count {
3279                                 pending_forwards.push(Readable::read(reader)?);
3280                         }
3281                         forward_htlcs.insert(short_channel_id, pending_forwards);
3282                 }
3283
3284                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
3285                 let mut claimable_htlcs = HashMap::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
3286                 for _ in 0..claimable_htlcs_count {
3287                         let payment_hash = Readable::read(reader)?;
3288                         let previous_hops_len: u64 = Readable::read(reader)?;
3289                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, 2));
3290                         for _ in 0..previous_hops_len {
3291                                 previous_hops.push(Readable::read(reader)?);
3292                         }
3293                         claimable_htlcs.insert(payment_hash, previous_hops);
3294                 }
3295
3296                 let channel_manager = ChannelManager {
3297                         genesis_hash,
3298                         fee_estimator: args.fee_estimator,
3299                         monitor: args.monitor,
3300                         chain_monitor: args.chain_monitor,
3301                         tx_broadcaster: args.tx_broadcaster,
3302
3303                         latest_block_height: AtomicUsize::new(latest_block_height as usize),
3304                         last_block_hash: Mutex::new(last_block_hash),
3305                         secp_ctx: Secp256k1::new(),
3306
3307                         channel_state: Mutex::new(ChannelHolder {
3308                                 by_id,
3309                                 short_to_id,
3310                                 next_forward: Instant::now(),
3311                                 forward_htlcs,
3312                                 claimable_htlcs,
3313                                 pending_msg_events: Vec::new(),
3314                         }),
3315                         our_network_key: args.keys_manager.get_node_secret(),
3316
3317                         pending_events: Mutex::new(Vec::new()),
3318                         total_consistency_lock: RwLock::new(()),
3319                         keys_manager: args.keys_manager,
3320                         logger: args.logger,
3321                         default_configuration: args.default_config,
3322                 };
3323
3324                 for close_res in closed_channels.drain(..) {
3325                         channel_manager.finish_force_close_channel(close_res);
3326                         //TODO: Broadcast channel update for closed channels, but only after we've made a
3327                         //connection or two.
3328                 }
3329
3330                 Ok((last_block_hash.clone(), channel_manager))
3331         }
3332 }
3333
3334 #[cfg(test)]
3335 mod tests {
3336         use chain::chaininterface;
3337         use chain::transaction::OutPoint;
3338         use chain::chaininterface::{ChainListener, ChainWatchInterface};
3339         use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor};
3340         use chain::keysinterface;
3341         use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
3342         use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,OnionKeys,RAACommitmentOrder, PaymentPreimage, PaymentHash};
3343         use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, ManyChannelMonitor};
3344         use ln::channel::{ACCEPTED_HTLC_SCRIPT_WEIGHT, OFFERED_HTLC_SCRIPT_WEIGHT};
3345         use ln::router::{Route, RouteHop, Router};
3346         use ln::msgs;
3347         use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate};
3348         use util::test_utils;
3349         use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
3350         use util::errors::APIError;
3351         use util::logger::Logger;
3352         use util::ser::{Writeable, Writer, ReadableArgs};
3353         use util::config::UserConfig;
3354
3355         use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
3356         use bitcoin::util::bip143;
3357         use bitcoin::util::address::Address;
3358         use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
3359         use bitcoin::blockdata::block::{Block, BlockHeader};
3360         use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType};
3361         use bitcoin::blockdata::script::{Builder, Script};
3362         use bitcoin::blockdata::opcodes;
3363         use bitcoin::blockdata::constants::genesis_block;
3364         use bitcoin::network::constants::Network;
3365
3366         use bitcoin_hashes::sha256::Hash as Sha256;
3367         use bitcoin_hashes::Hash;
3368
3369         use hex;
3370
3371         use secp256k1::{Secp256k1, Message};
3372         use secp256k1::key::{PublicKey,SecretKey};
3373
3374         use rand::{thread_rng,Rng};
3375
3376         use std::cell::RefCell;
3377         use std::collections::{BTreeSet, HashMap, HashSet};
3378         use std::default::Default;
3379         use std::rc::Rc;
3380         use std::sync::{Arc, Mutex};
3381         use std::sync::atomic::Ordering;
3382         use std::time::Instant;
3383         use std::mem;
3384
3385         fn build_test_onion_keys() -> Vec<OnionKeys> {
3386                 // Keys from BOLT 4, used in both test vector tests
3387                 let secp_ctx = Secp256k1::new();
3388
3389                 let route = Route {
3390                         hops: vec!(
3391                                         RouteHop {
3392                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
3393                                                 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
3394                                         },
3395                                         RouteHop {
3396                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
3397                                                 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
3398                                         },
3399                                         RouteHop {
3400                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
3401                                                 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
3402                                         },
3403                                         RouteHop {
3404                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..]).unwrap(),
3405                                                 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
3406                                         },
3407                                         RouteHop {
3408                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145").unwrap()[..]).unwrap(),
3409                                                 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
3410                                         },
3411                         ),
3412                 };
3413
3414                 let session_priv = SecretKey::from_slice(&secp_ctx, &hex::decode("4141414141414141414141414141414141414141414141414141414141414141").unwrap()[..]).unwrap();
3415
3416                 let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
3417                 assert_eq!(onion_keys.len(), route.hops.len());
3418                 onion_keys
3419         }
3420
3421         #[test]
3422         fn onion_vectors() {
3423                 // Packet creation test vectors from BOLT 4
3424                 let onion_keys = build_test_onion_keys();
3425
3426                 assert_eq!(onion_keys[0].shared_secret[..], hex::decode("53eb63ea8a3fec3b3cd433b85cd62a4b145e1dda09391b348c4e1cd36a03ea66").unwrap()[..]);
3427                 assert_eq!(onion_keys[0].blinding_factor[..], hex::decode("2ec2e5da605776054187180343287683aa6a51b4b1c04d6dd49c45d8cffb3c36").unwrap()[..]);
3428                 assert_eq!(onion_keys[0].ephemeral_pubkey.serialize()[..], hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]);
3429                 assert_eq!(onion_keys[0].rho, hex::decode("ce496ec94def95aadd4bec15cdb41a740c9f2b62347c4917325fcc6fb0453986").unwrap()[..]);
3430                 assert_eq!(onion_keys[0].mu, hex::decode("b57061dc6d0a2b9f261ac410c8b26d64ac5506cbba30267a649c28c179400eba").unwrap()[..]);
3431
3432                 assert_eq!(onion_keys[1].shared_secret[..], hex::decode("a6519e98832a0b179f62123b3567c106db99ee37bef036e783263602f3488fae").unwrap()[..]);
3433                 assert_eq!(onion_keys[1].blinding_factor[..], hex::decode("bf66c28bc22e598cfd574a1931a2bafbca09163df2261e6d0056b2610dab938f").unwrap()[..]);
3434                 assert_eq!(onion_keys[1].ephemeral_pubkey.serialize()[..], hex::decode("028f9438bfbf7feac2e108d677e3a82da596be706cc1cf342b75c7b7e22bf4e6e2").unwrap()[..]);
3435                 assert_eq!(onion_keys[1].rho, hex::decode("450ffcabc6449094918ebe13d4f03e433d20a3d28a768203337bc40b6e4b2c59").unwrap()[..]);
3436                 assert_eq!(onion_keys[1].mu, hex::decode("05ed2b4a3fb023c2ff5dd6ed4b9b6ea7383f5cfe9d59c11d121ec2c81ca2eea9").unwrap()[..]);
3437
3438                 assert_eq!(onion_keys[2].shared_secret[..], hex::decode("3a6b412548762f0dbccce5c7ae7bb8147d1caf9b5471c34120b30bc9c04891cc").unwrap()[..]);
3439                 assert_eq!(onion_keys[2].blinding_factor[..], hex::decode("a1f2dadd184eb1627049673f18c6325814384facdee5bfd935d9cb031a1698a5").unwrap()[..]);
3440                 assert_eq!(onion_keys[2].ephemeral_pubkey.serialize()[..], hex::decode("03bfd8225241ea71cd0843db7709f4c222f62ff2d4516fd38b39914ab6b83e0da0").unwrap()[..]);
3441                 assert_eq!(onion_keys[2].rho, hex::decode("11bf5c4f960239cb37833936aa3d02cea82c0f39fd35f566109c41f9eac8deea").unwrap()[..]);
3442                 assert_eq!(onion_keys[2].mu, hex::decode("caafe2820fa00eb2eeb78695ae452eba38f5a53ed6d53518c5c6edf76f3f5b78").unwrap()[..]);
3443
3444                 assert_eq!(onion_keys[3].shared_secret[..], hex::decode("21e13c2d7cfe7e18836df50872466117a295783ab8aab0e7ecc8c725503ad02d").unwrap()[..]);
3445                 assert_eq!(onion_keys[3].blinding_factor[..], hex::decode("7cfe0b699f35525029ae0fa437c69d0f20f7ed4e3916133f9cacbb13c82ff262").unwrap()[..]);
3446                 assert_eq!(onion_keys[3].ephemeral_pubkey.serialize()[..], hex::decode("031dde6926381289671300239ea8e57ffaf9bebd05b9a5b95beaf07af05cd43595").unwrap()[..]);
3447                 assert_eq!(onion_keys[3].rho, hex::decode("cbe784ab745c13ff5cffc2fbe3e84424aa0fd669b8ead4ee562901a4a4e89e9e").unwrap()[..]);
3448                 assert_eq!(onion_keys[3].mu, hex::decode("5052aa1b3d9f0655a0932e50d42f0c9ba0705142c25d225515c45f47c0036ee9").unwrap()[..]);
3449
3450                 assert_eq!(onion_keys[4].shared_secret[..], hex::decode("b5756b9b542727dbafc6765a49488b023a725d631af688fc031217e90770c328").unwrap()[..]);
3451                 assert_eq!(onion_keys[4].blinding_factor[..], hex::decode("c96e00dddaf57e7edcd4fb5954be5b65b09f17cb6d20651b4e90315be5779205").unwrap()[..]);
3452                 assert_eq!(onion_keys[4].ephemeral_pubkey.serialize()[..], hex::decode("03a214ebd875aab6ddfd77f22c5e7311d7f77f17a169e599f157bbcdae8bf071f4").unwrap()[..]);
3453                 assert_eq!(onion_keys[4].rho, hex::decode("034e18b8cc718e8af6339106e706c52d8df89e2b1f7e9142d996acf88df8799b").unwrap()[..]);
3454                 assert_eq!(onion_keys[4].mu, hex::decode("8e45e5c61c2b24cb6382444db6698727afb063adecd72aada233d4bf273d975a").unwrap()[..]);
3455
3456                 // Test vectors below are flat-out wrong: they claim to set outgoing_cltv_value to non-0 :/
3457                 let payloads = vec!(
3458                         msgs::OnionHopData {
3459                                 realm: 0,
3460                                 data: msgs::OnionRealm0HopData {
3461                                         short_channel_id: 0,
3462                                         amt_to_forward: 0,
3463                                         outgoing_cltv_value: 0,
3464                                 },
3465                                 hmac: [0; 32],
3466                         },
3467                         msgs::OnionHopData {
3468                                 realm: 0,
3469                                 data: msgs::OnionRealm0HopData {
3470                                         short_channel_id: 0x0101010101010101,
3471                                         amt_to_forward: 0x0100000001,
3472                                         outgoing_cltv_value: 0,
3473                                 },
3474                                 hmac: [0; 32],
3475                         },
3476                         msgs::OnionHopData {
3477                                 realm: 0,
3478                                 data: msgs::OnionRealm0HopData {
3479                                         short_channel_id: 0x0202020202020202,
3480                                         amt_to_forward: 0x0200000002,
3481                                         outgoing_cltv_value: 0,
3482                                 },
3483                                 hmac: [0; 32],
3484                         },
3485                         msgs::OnionHopData {
3486                                 realm: 0,
3487                                 data: msgs::OnionRealm0HopData {
3488                                         short_channel_id: 0x0303030303030303,
3489                                         amt_to_forward: 0x0300000003,
3490                                         outgoing_cltv_value: 0,
3491                                 },
3492                                 hmac: [0; 32],
3493                         },
3494                         msgs::OnionHopData {
3495                                 realm: 0,
3496                                 data: msgs::OnionRealm0HopData {
3497                                         short_channel_id: 0x0404040404040404,
3498                                         amt_to_forward: 0x0400000004,
3499                                         outgoing_cltv_value: 0,
3500                                 },
3501                                 hmac: [0; 32],
3502                         },
3503                 );
3504
3505                 let packet = ChannelManager::construct_onion_packet(payloads, onion_keys, &PaymentHash([0x42; 32]));
3506                 // Just check the final packet encoding, as it includes all the per-hop vectors in it
3507                 // anyway...
3508                 assert_eq!(packet.encode(), hex::decode("0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619e5f14350c2a76fc232b5e46d421e9615471ab9e0bc887beff8c95fdb878f7b3a716a996c7845c93d90e4ecbb9bde4ece2f69425c99e4bc820e44485455f135edc0d10f7d61ab590531cf08000179a333a347f8b4072f216400406bdf3bf038659793d4a1fd7b246979e3150a0a4cb052c9ec69acf0f48c3d39cd55675fe717cb7d80ce721caad69320c3a469a202f1e468c67eaf7a7cd8226d0fd32f7b48084dca885d56047694762b67021713ca673929c163ec36e04e40ca8e1c6d17569419d3039d9a1ec866abe044a9ad635778b961fc0776dc832b3a451bd5d35072d2269cf9b040f6b7a7dad84fb114ed413b1426cb96ceaf83825665ed5a1d002c1687f92465b49ed4c7f0218ff8c6c7dd7221d589c65b3b9aaa71a41484b122846c7c7b57e02e679ea8469b70e14fe4f70fee4d87b910cf144be6fe48eef24da475c0b0bcc6565ae82cd3f4e3b24c76eaa5616c6111343306ab35c1fe5ca4a77c0e314ed7dba39d6f1e0de791719c241a939cc493bea2bae1c1e932679ea94d29084278513c77b899cc98059d06a27d171b0dbdf6bee13ddc4fc17a0c4d2827d488436b57baa167544138ca2e64a11b43ac8a06cd0c2fba2d4d900ed2d9205305e2d7383cc98dacb078133de5f6fb6bed2ef26ba92cea28aafc3b9948dd9ae5559e8bd6920b8cea462aa445ca6a95e0e7ba52961b181c79e73bd581821df2b10173727a810c92b83b5ba4a0403eb710d2ca10689a35bec6c3a708e9e92f7d78ff3c5d9989574b00c6736f84c199256e76e19e78f0c98a9d580b4a658c84fc8f2096c2fbea8f5f8c59d0fdacb3be2802ef802abbecb3aba4acaac69a0e965abd8981e9896b1f6ef9d60f7a164b371af869fd0e48073742825e9434fc54da837e120266d53302954843538ea7c6c3dbfb4ff3b2fdbe244437f2a153ccf7bdb4c92aa08102d4f3cff2ae5ef86fab4653595e6a5837fa2f3e29f27a9cde5966843fb847a4a61f1e76c281fe8bb2b0a181d096100db5a1a5ce7a910238251a43ca556712eaadea167fb4d7d75825e440f3ecd782036d7574df8bceacb397abefc5f5254d2722215c53ff54af8299aaaad642c6d72a14d27882d9bbd539e1cc7a527526ba89b8c037ad09120e98ab042d3e8652b31ae0e478516bfaf88efca9f3676ffe99d2819dcaeb7610a626695f53117665d267d3f7abebd6bbd6733f645c72c389f03855bdf1e4b8075b516569b118233a0f0971d24b83113c0b096f5216a207ca99a7cddc81c130923fe3d91e7508c9ac5f2e914ff5dccab9e558566fa14efb34ac98d878580814b94b73acbfde9072f30b881f7f0fff42d4045d1ace6322d86a97d164aa84d93a60498065cc7c20e636f5862dc81531a88c60305a2e59a985be327a6902e4bed986dbf4a0b50c217af0ea7fdf9ab37f9ea1a1aaa72f54cf40154ea9b269f1a7c09f9f43245109431a175d50e2db0132337baa0ef97eed0fcf20489da36b79a1172faccc2f7ded7c60e00694282d93359c4682135642bc81f433574aa8ef0c97b4ade7ca372c5ffc23c7eddd839bab4e0f14d6df15c9dbeab176bec8b5701cf054eb3072f6dadc98f88819042bf10c407516ee58bce33fbe3b3d86a54255e577db4598e30a135361528c101683a5fcde7e8ba53f3456254be8f45fe3a56120ae96ea3773631fcb3873aa3abd91bcff00bd38bd43697a2e789e00da6077482e7b1b1a677b5afae4c54e6cbdf7377b694eb7d7a5b913476a5be923322d3de06060fd5e819635232a2cf4f0731da13b8546d1d6d4f8d75b9fce6c2341a71b0ea6f780df54bfdb0dd5cd9855179f602f9172307c7268724c3618e6817abd793adc214a0dc0bc616816632f27ea336fb56dfd").unwrap());
3509         }
3510
3511         #[test]
3512         fn test_failure_packet_onion() {
3513                 // Returning Errors test vectors from BOLT 4
3514
3515                 let onion_keys = build_test_onion_keys();
3516                 let onion_error = ChannelManager::build_failure_packet(&onion_keys[4].shared_secret[..], 0x2002, &[0; 0]);
3517                 assert_eq!(onion_error.encode(), hex::decode("4c2fc8bc08510334b6833ad9c3e79cd1b52ae59dfe5c2a4b23ead50f09f7ee0b0002200200fe0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap());
3518
3519                 let onion_packet_1 = ChannelManager::encrypt_failure_packet(&onion_keys[4].shared_secret[..], &onion_error.encode()[..]);
3520                 assert_eq!(onion_packet_1.data, hex::decode("a5e6bd0c74cb347f10cce367f949098f2457d14c046fd8a22cb96efb30b0fdcda8cb9168b50f2fd45edd73c1b0c8b33002df376801ff58aaa94000bf8a86f92620f343baef38a580102395ae3abf9128d1047a0736ff9b83d456740ebbb4aeb3aa9737f18fb4afb4aa074fb26c4d702f42968888550a3bded8c05247e045b866baef0499f079fdaeef6538f31d44deafffdfd3afa2fb4ca9082b8f1c465371a9894dd8c243fb4847e004f5256b3e90e2edde4c9fb3082ddfe4d1e734cacd96ef0706bf63c9984e22dc98851bcccd1c3494351feb458c9c6af41c0044bea3c47552b1d992ae542b17a2d0bba1a096c78d169034ecb55b6e3a7263c26017f033031228833c1daefc0dedb8cf7c3e37c9c37ebfe42f3225c326e8bcfd338804c145b16e34e4").unwrap());
3521
3522                 let onion_packet_2 = ChannelManager::encrypt_failure_packet(&onion_keys[3].shared_secret[..], &onion_packet_1.data[..]);
3523                 assert_eq!(onion_packet_2.data, hex::decode("c49a1ce81680f78f5f2000cda36268de34a3f0a0662f55b4e837c83a8773c22aa081bab1616a0011585323930fa5b9fae0c85770a2279ff59ec427ad1bbff9001c0cd1497004bd2a0f68b50704cf6d6a4bf3c8b6a0833399a24b3456961ba00736785112594f65b6b2d44d9f5ea4e49b5e1ec2af978cbe31c67114440ac51a62081df0ed46d4a3df295da0b0fe25c0115019f03f15ec86fabb4c852f83449e812f141a9395b3f70b766ebbd4ec2fae2b6955bd8f32684c15abfe8fd3a6261e52650e8807a92158d9f1463261a925e4bfba44bd20b166d532f0017185c3a6ac7957adefe45559e3072c8dc35abeba835a8cb01a71a15c736911126f27d46a36168ca5ef7dccd4e2886212602b181463e0dd30185c96348f9743a02aca8ec27c0b90dca270").unwrap());
3524
3525                 let onion_packet_3 = ChannelManager::encrypt_failure_packet(&onion_keys[2].shared_secret[..], &onion_packet_2.data[..]);
3526                 assert_eq!(onion_packet_3.data, hex::decode("a5d3e8634cfe78b2307d87c6d90be6fe7855b4f2cc9b1dfb19e92e4b79103f61ff9ac25f412ddfb7466e74f81b3e545563cdd8f5524dae873de61d7bdfccd496af2584930d2b566b4f8d3881f8c043df92224f38cf094cfc09d92655989531524593ec6d6caec1863bdfaa79229b5020acc034cd6deeea1021c50586947b9b8e6faa83b81fbfa6133c0af5d6b07c017f7158fa94f0d206baf12dda6b68f785b773b360fd0497e16cc402d779c8d48d0fa6315536ef0660f3f4e1865f5b38ea49c7da4fd959de4e83ff3ab686f059a45c65ba2af4a6a79166aa0f496bf04d06987b6d2ea205bdb0d347718b9aeff5b61dfff344993a275b79717cd815b6ad4c0beb568c4ac9c36ff1c315ec1119a1993c4b61e6eaa0375e0aaf738ac691abd3263bf937e3").unwrap());
3527
3528                 let onion_packet_4 = ChannelManager::encrypt_failure_packet(&onion_keys[1].shared_secret[..], &onion_packet_3.data[..]);
3529                 assert_eq!(onion_packet_4.data, hex::decode("aac3200c4968f56b21f53e5e374e3a2383ad2b1b6501bbcc45abc31e59b26881b7dfadbb56ec8dae8857add94e6702fb4c3a4de22e2e669e1ed926b04447fc73034bb730f4932acd62727b75348a648a1128744657ca6a4e713b9b646c3ca66cac02cdab44dd3439890ef3aaf61708714f7375349b8da541b2548d452d84de7084bb95b3ac2345201d624d31f4d52078aa0fa05a88b4e20202bd2b86ac5b52919ea305a8949de95e935eed0319cf3cf19ebea61d76ba92532497fcdc9411d06bcd4275094d0a4a3c5d3a945e43305a5a9256e333e1f64dbca5fcd4e03a39b9012d197506e06f29339dfee3331995b21615337ae060233d39befea925cc262873e0530408e6990f1cbd233a150ef7b004ff6166c70c68d9f8c853c1abca640b8660db2921").unwrap());
3530
3531                 let onion_packet_5 = ChannelManager::encrypt_failure_packet(&onion_keys[0].shared_secret[..], &onion_packet_4.data[..]);
3532                 assert_eq!(onion_packet_5.data, hex::decode("9c5add3963fc7f6ed7f148623c84134b5647e1306419dbe2174e523fa9e2fbed3a06a19f899145610741c83ad40b7712aefaddec8c6baf7325d92ea4ca4d1df8bce517f7e54554608bf2bd8071a4f52a7a2f7ffbb1413edad81eeea5785aa9d990f2865dc23b4bc3c301a94eec4eabebca66be5cf638f693ec256aec514620cc28ee4a94bd9565bc4d4962b9d3641d4278fb319ed2b84de5b665f307a2db0f7fbb757366067d88c50f7e829138fde4f78d39b5b5802f1b92a8a820865af5cc79f9f30bc3f461c66af95d13e5e1f0381c184572a91dee1c849048a647a1158cf884064deddbf1b0b88dfe2f791428d0ba0f6fb2f04e14081f69165ae66d9297c118f0907705c9c4954a199bae0bb96fad763d690e7daa6cfda59ba7f2c8d11448b604d12d").unwrap());
3533         }
3534
3535         fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
3536                 assert!(chain.does_match_tx(tx));
3537                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3538                 chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
3539                 for i in 2..100 {
3540                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3541                         chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
3542                 }
3543         }
3544
3545         struct Node {
3546                 chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
3547                 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
3548                 chan_monitor: Arc<test_utils::TestChannelMonitor>,
3549                 keys_manager: Arc<test_utils::TestKeysInterface>,
3550                 node: Arc<ChannelManager>,
3551                 router: Router,
3552                 node_seed: [u8; 32],
3553                 network_payment_count: Rc<RefCell<u8>>,
3554                 network_chan_count: Rc<RefCell<u32>>,
3555         }
3556         impl Drop for Node {
3557                 fn drop(&mut self) {
3558                         if !::std::thread::panicking() {
3559                                 // Check that we processed all pending events
3560                                 assert_eq!(self.node.get_and_clear_pending_msg_events().len(), 0);
3561                                 assert_eq!(self.node.get_and_clear_pending_events().len(), 0);
3562                                 assert_eq!(self.chan_monitor.added_monitors.lock().unwrap().len(), 0);
3563                         }
3564                 }
3565         }
3566
3567         fn create_chan_between_nodes(node_a: &Node, node_b: &Node) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3568                 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001)
3569         }
3570
3571         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) {
3572                 let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat);
3573                 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
3574                 (announcement, as_update, bs_update, channel_id, tx)
3575         }
3576
3577         macro_rules! get_revoke_commit_msgs {
3578                 ($node: expr, $node_id: expr) => {
3579                         {
3580                                 let events = $node.node.get_and_clear_pending_msg_events();
3581                                 assert_eq!(events.len(), 2);
3582                                 (match events[0] {
3583                                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3584                                                 assert_eq!(*node_id, $node_id);
3585                                                 (*msg).clone()
3586                                         },
3587                                         _ => panic!("Unexpected event"),
3588                                 }, match events[1] {
3589                                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3590                                                 assert_eq!(*node_id, $node_id);
3591                                                 assert!(updates.update_add_htlcs.is_empty());
3592                                                 assert!(updates.update_fulfill_htlcs.is_empty());
3593                                                 assert!(updates.update_fail_htlcs.is_empty());
3594                                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
3595                                                 assert!(updates.update_fee.is_none());
3596                                                 updates.commitment_signed.clone()
3597                                         },
3598                                         _ => panic!("Unexpected event"),
3599                                 })
3600                         }
3601                 }
3602         }
3603
3604         macro_rules! get_event_msg {
3605                 ($node: expr, $event_type: path, $node_id: expr) => {
3606                         {
3607                                 let events = $node.node.get_and_clear_pending_msg_events();
3608                                 assert_eq!(events.len(), 1);
3609                                 match events[0] {
3610                                         $event_type { ref node_id, ref msg } => {
3611                                                 assert_eq!(*node_id, $node_id);
3612                                                 (*msg).clone()
3613                                         },
3614                                         _ => panic!("Unexpected event"),
3615                                 }
3616                         }
3617                 }
3618         }
3619
3620         macro_rules! get_htlc_update_msgs {
3621                 ($node: expr, $node_id: expr) => {
3622                         {
3623                                 let events = $node.node.get_and_clear_pending_msg_events();
3624                                 assert_eq!(events.len(), 1);
3625                                 match events[0] {
3626                                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3627                                                 assert_eq!(*node_id, $node_id);
3628                                                 (*updates).clone()
3629                                         },
3630                                         _ => panic!("Unexpected event"),
3631                                 }
3632                         }
3633                 }
3634         }
3635
3636         macro_rules! get_feerate {
3637                 ($node: expr, $channel_id: expr) => {
3638                         {
3639                                 let chan_lock = $node.node.channel_state.lock().unwrap();
3640                                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
3641                                 chan.get_feerate()
3642                         }
3643                 }
3644         }
3645
3646
3647         fn create_chan_between_nodes_with_value_init(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> Transaction {
3648                 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
3649                 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();
3650                 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();
3651
3652                 let chan_id = *node_a.network_chan_count.borrow();
3653                 let tx;
3654                 let funding_output;
3655
3656                 let events_2 = node_a.node.get_and_clear_pending_events();
3657                 assert_eq!(events_2.len(), 1);
3658                 match events_2[0] {
3659                         Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
3660                                 assert_eq!(*channel_value_satoshis, channel_value);
3661                                 assert_eq!(user_channel_id, 42);
3662
3663                                 tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
3664                                         value: *channel_value_satoshis, script_pubkey: output_script.clone(),
3665                                 }]};
3666                                 funding_output = OutPoint::new(tx.txid(), 0);
3667
3668                                 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
3669                                 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3670                                 assert_eq!(added_monitors.len(), 1);
3671                                 assert_eq!(added_monitors[0].0, funding_output);
3672                                 added_monitors.clear();
3673                         },
3674                         _ => panic!("Unexpected event"),
3675                 }
3676
3677                 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();
3678                 {
3679                         let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
3680                         assert_eq!(added_monitors.len(), 1);
3681                         assert_eq!(added_monitors[0].0, funding_output);
3682                         added_monitors.clear();
3683                 }
3684
3685                 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();
3686                 {
3687                         let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3688                         assert_eq!(added_monitors.len(), 1);
3689                         assert_eq!(added_monitors[0].0, funding_output);
3690                         added_monitors.clear();
3691                 }
3692
3693                 let events_4 = node_a.node.get_and_clear_pending_events();
3694                 assert_eq!(events_4.len(), 1);
3695                 match events_4[0] {
3696                         Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
3697                                 assert_eq!(user_channel_id, 42);
3698                                 assert_eq!(*funding_txo, funding_output);
3699                         },
3700                         _ => panic!("Unexpected event"),
3701                 };
3702
3703                 tx
3704         }
3705
3706         fn create_chan_between_nodes_with_value_confirm(node_a: &Node, node_b: &Node, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
3707                 confirm_transaction(&node_b.chain_monitor, &tx, tx.version);
3708                 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();
3709
3710                 let channel_id;
3711
3712                 confirm_transaction(&node_a.chain_monitor, &tx, tx.version);
3713                 let events_6 = node_a.node.get_and_clear_pending_msg_events();
3714                 assert_eq!(events_6.len(), 2);
3715                 ((match events_6[0] {
3716                         MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3717                                 channel_id = msg.channel_id.clone();
3718                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
3719                                 msg.clone()
3720                         },
3721                         _ => panic!("Unexpected event"),
3722                 }, match events_6[1] {
3723                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3724                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
3725                                 msg.clone()
3726                         },
3727                         _ => panic!("Unexpected event"),
3728                 }), channel_id)
3729         }
3730
3731         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) {
3732                 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat);
3733                 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
3734                 (msgs, chan_id, tx)
3735         }
3736
3737         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) {
3738                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0).unwrap();
3739                 let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
3740                 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1).unwrap();
3741
3742                 let events_7 = node_b.node.get_and_clear_pending_msg_events();
3743                 assert_eq!(events_7.len(), 1);
3744                 let (announcement, bs_update) = match events_7[0] {
3745                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3746                                 (msg, update_msg)
3747                         },
3748                         _ => panic!("Unexpected event"),
3749                 };
3750
3751                 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs).unwrap();
3752                 let events_8 = node_a.node.get_and_clear_pending_msg_events();
3753                 assert_eq!(events_8.len(), 1);
3754                 let as_update = match events_8[0] {
3755                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3756                                 assert!(*announcement == *msg);
3757                                 assert_eq!(update_msg.contents.short_channel_id, announcement.contents.short_channel_id);
3758                                 assert_eq!(update_msg.contents.short_channel_id, bs_update.contents.short_channel_id);
3759                                 update_msg
3760                         },
3761                         _ => panic!("Unexpected event"),
3762                 };
3763
3764                 *node_a.network_chan_count.borrow_mut() += 1;
3765
3766                 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
3767         }
3768
3769         fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3770                 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001)
3771         }
3772
3773         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) {
3774                 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat);
3775                 for node in nodes {
3776                         assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
3777                         node.router.handle_channel_update(&chan_announcement.1).unwrap();
3778                         node.router.handle_channel_update(&chan_announcement.2).unwrap();
3779                 }
3780                 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
3781         }
3782
3783         macro_rules! check_spends {
3784                 ($tx: expr, $spends_tx: expr) => {
3785                         {
3786                                 let mut funding_tx_map = HashMap::new();
3787                                 let spends_tx = $spends_tx;
3788                                 funding_tx_map.insert(spends_tx.txid(), spends_tx);
3789                                 $tx.verify(&funding_tx_map).unwrap();
3790                         }
3791                 }
3792         }
3793
3794         macro_rules! get_closing_signed_broadcast {
3795                 ($node: expr, $dest_pubkey: expr) => {
3796                         {
3797                                 let events = $node.get_and_clear_pending_msg_events();
3798                                 assert!(events.len() == 1 || events.len() == 2);
3799                                 (match events[events.len() - 1] {
3800                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
3801                                                 assert_eq!(msg.contents.flags & 2, 2);
3802                                                 msg.clone()
3803                                         },
3804                                         _ => panic!("Unexpected event"),
3805                                 }, if events.len() == 2 {
3806                                         match events[0] {
3807                                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3808                                                         assert_eq!(*node_id, $dest_pubkey);
3809                                                         Some(msg.clone())
3810                                                 },
3811                                                 _ => panic!("Unexpected event"),
3812                                         }
3813                                 } else { None })
3814                         }
3815                 }
3816         }
3817
3818         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) {
3819                 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) };
3820                 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
3821                 let (tx_a, tx_b);
3822
3823                 node_a.close_channel(channel_id).unwrap();
3824                 node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id())).unwrap();
3825
3826                 let events_1 = node_b.get_and_clear_pending_msg_events();
3827                 assert!(events_1.len() >= 1);
3828                 let shutdown_b = match events_1[0] {
3829                         MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
3830                                 assert_eq!(node_id, &node_a.get_our_node_id());
3831                                 msg.clone()
3832                         },
3833                         _ => panic!("Unexpected event"),
3834                 };
3835
3836                 let closing_signed_b = if !close_inbound_first {
3837                         assert_eq!(events_1.len(), 1);
3838                         None
3839                 } else {
3840                         Some(match events_1[1] {
3841                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3842                                         assert_eq!(node_id, &node_a.get_our_node_id());
3843                                         msg.clone()
3844                                 },
3845                                 _ => panic!("Unexpected event"),
3846                         })
3847                 };
3848
3849                 node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b).unwrap();
3850                 let (as_update, bs_update) = if close_inbound_first {
3851                         assert!(node_a.get_and_clear_pending_msg_events().is_empty());
3852                         node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3853                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3854                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3855                         let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3856
3857                         node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
3858                         let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3859                         assert!(none_b.is_none());
3860                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3861                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3862                         (as_update, bs_update)
3863                 } else {
3864                         let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
3865
3866                         node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a).unwrap();
3867                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3868                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3869                         let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3870
3871                         node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3872                         let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3873                         assert!(none_a.is_none());
3874                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3875                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3876                         (as_update, bs_update)
3877                 };
3878                 assert_eq!(tx_a, tx_b);
3879                 check_spends!(tx_a, funding_tx);
3880
3881                 (as_update, bs_update, tx_a)
3882         }
3883
3884         struct SendEvent {
3885                 node_id: PublicKey,
3886                 msgs: Vec<msgs::UpdateAddHTLC>,
3887                 commitment_msg: msgs::CommitmentSigned,
3888         }
3889         impl SendEvent {
3890                 fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
3891                         assert!(updates.update_fulfill_htlcs.is_empty());
3892                         assert!(updates.update_fail_htlcs.is_empty());
3893                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3894                         assert!(updates.update_fee.is_none());
3895                         SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
3896                 }
3897
3898                 fn from_event(event: MessageSendEvent) -> SendEvent {
3899                         match event {
3900                                 MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
3901                                 _ => panic!("Unexpected event type!"),
3902                         }
3903                 }
3904
3905                 fn from_node(node: &Node) -> SendEvent {
3906                         let mut events = node.node.get_and_clear_pending_msg_events();
3907                         assert_eq!(events.len(), 1);
3908                         SendEvent::from_event(events.pop().unwrap())
3909                 }
3910         }
3911
3912         macro_rules! check_added_monitors {
3913                 ($node: expr, $count: expr) => {
3914                         {
3915                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
3916                                 assert_eq!(added_monitors.len(), $count);
3917                                 added_monitors.clear();
3918                         }
3919                 }
3920         }
3921
3922         macro_rules! commitment_signed_dance {
3923                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
3924                         {
3925                                 check_added_monitors!($node_a, 0);
3926                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3927                                 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3928                                 check_added_monitors!($node_a, 1);
3929                                 commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
3930                         }
3931                 };
3932                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
3933                         {
3934                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
3935                                 check_added_monitors!($node_b, 0);
3936                                 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3937                                 $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
3938                                 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3939                                 check_added_monitors!($node_b, 1);
3940                                 $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed).unwrap();
3941                                 let (bs_revoke_and_ack, extra_msg_option) = {
3942                                         let events = $node_b.node.get_and_clear_pending_msg_events();
3943                                         assert!(events.len() <= 2);
3944                                         (match events[0] {
3945                                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3946                                                         assert_eq!(*node_id, $node_a.node.get_our_node_id());
3947                                                         (*msg).clone()
3948                                                 },
3949                                                 _ => panic!("Unexpected event"),
3950                                         }, events.get(1).map(|e| e.clone()))
3951                                 };
3952                                 check_added_monitors!($node_b, 1);
3953                                 if $fail_backwards {
3954                                         assert!($node_a.node.get_and_clear_pending_events().is_empty());
3955                                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3956                                 }
3957                                 (extra_msg_option, bs_revoke_and_ack)
3958                         }
3959                 };
3960                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
3961                         {
3962                                 check_added_monitors!($node_a, 0);
3963                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3964                                 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3965                                 check_added_monitors!($node_a, 1);
3966                                 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
3967                                 assert!(extra_msg_option.is_none());
3968                                 bs_revoke_and_ack
3969                         }
3970                 };
3971                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
3972                         {
3973                                 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
3974                                 $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
3975                                 {
3976                                         let mut added_monitors = $node_a.chan_monitor.added_monitors.lock().unwrap();
3977                                         if $fail_backwards {
3978                                                 assert_eq!(added_monitors.len(), 2);
3979                                                 assert!(added_monitors[0].0 != added_monitors[1].0);
3980                                         } else {
3981                                                 assert_eq!(added_monitors.len(), 1);
3982                                         }
3983                                         added_monitors.clear();
3984                                 }
3985                                 extra_msg_option
3986                         }
3987                 };
3988                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
3989                         {
3990                                 assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
3991                         }
3992                 };
3993                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
3994                         {
3995                                 commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
3996                                 if $fail_backwards {
3997                                         let channel_state = $node_a.node.channel_state.lock().unwrap();
3998                                         assert_eq!(channel_state.pending_msg_events.len(), 1);
3999                                         if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
4000                                                 assert_ne!(*node_id, $node_b.node.get_our_node_id());
4001                                         } else { panic!("Unexpected event"); }
4002                                 } else {
4003                                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
4004                                 }
4005                         }
4006                 }
4007         }
4008
4009         macro_rules! get_payment_preimage_hash {
4010                 ($node: expr) => {
4011                         {
4012                                 let payment_preimage = PaymentPreimage([*$node.network_payment_count.borrow(); 32]);
4013                                 *$node.network_payment_count.borrow_mut() += 1;
4014                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
4015                                 (payment_preimage, payment_hash)
4016                         }
4017                 }
4018         }
4019
4020         fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
4021                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4022
4023                 let mut payment_event = {
4024                         origin_node.node.send_payment(route, our_payment_hash).unwrap();
4025                         check_added_monitors!(origin_node, 1);
4026
4027                         let mut events = origin_node.node.get_and_clear_pending_msg_events();
4028                         assert_eq!(events.len(), 1);
4029                         SendEvent::from_event(events.remove(0))
4030                 };
4031                 let mut prev_node = origin_node;
4032
4033                 for (idx, &node) in expected_route.iter().enumerate() {
4034                         assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
4035
4036                         node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4037                         check_added_monitors!(node, 0);
4038                         commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
4039
4040                         let events_1 = node.node.get_and_clear_pending_events();
4041                         assert_eq!(events_1.len(), 1);
4042                         match events_1[0] {
4043                                 Event::PendingHTLCsForwardable { .. } => { },
4044                                 _ => panic!("Unexpected event"),
4045                         };
4046
4047                         node.node.channel_state.lock().unwrap().next_forward = Instant::now();
4048                         node.node.process_pending_htlc_forwards();
4049
4050                         if idx == expected_route.len() - 1 {
4051                                 let events_2 = node.node.get_and_clear_pending_events();
4052                                 assert_eq!(events_2.len(), 1);
4053                                 match events_2[0] {
4054                                         Event::PaymentReceived { ref payment_hash, amt } => {
4055                                                 assert_eq!(our_payment_hash, *payment_hash);
4056                                                 assert_eq!(amt, recv_value);
4057                                         },
4058                                         _ => panic!("Unexpected event"),
4059                                 }
4060                         } else {
4061                                 let mut events_2 = node.node.get_and_clear_pending_msg_events();
4062                                 assert_eq!(events_2.len(), 1);
4063                                 check_added_monitors!(node, 1);
4064                                 payment_event = SendEvent::from_event(events_2.remove(0));
4065                                 assert_eq!(payment_event.msgs.len(), 1);
4066                         }
4067
4068                         prev_node = node;
4069                 }
4070
4071                 (our_payment_preimage, our_payment_hash)
4072         }
4073
4074         fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: PaymentPreimage) {
4075                 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
4076                 check_added_monitors!(expected_route.last().unwrap(), 1);
4077
4078                 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
4079                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4080                 macro_rules! get_next_msgs {
4081                         ($node: expr) => {
4082                                 {
4083                                         let events = $node.node.get_and_clear_pending_msg_events();
4084                                         assert_eq!(events.len(), 1);
4085                                         match events[0] {
4086                                                 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 } } => {
4087                                                         assert!(update_add_htlcs.is_empty());
4088                                                         assert_eq!(update_fulfill_htlcs.len(), 1);
4089                                                         assert!(update_fail_htlcs.is_empty());
4090                                                         assert!(update_fail_malformed_htlcs.is_empty());
4091                                                         assert!(update_fee.is_none());
4092                                                         expected_next_node = node_id.clone();
4093                                                         Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()))
4094                                                 },
4095                                                 _ => panic!("Unexpected event"),
4096                                         }
4097                                 }
4098                         }
4099                 }
4100
4101                 macro_rules! last_update_fulfill_dance {
4102                         ($node: expr, $prev_node: expr) => {
4103                                 {
4104                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4105                                         check_added_monitors!($node, 0);
4106                                         assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4107                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4108                                 }
4109                         }
4110                 }
4111                 macro_rules! mid_update_fulfill_dance {
4112                         ($node: expr, $prev_node: expr, $new_msgs: expr) => {
4113                                 {
4114                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4115                                         check_added_monitors!($node, 1);
4116                                         let new_next_msgs = if $new_msgs {
4117                                                 get_next_msgs!($node)
4118                                         } else {
4119                                                 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4120                                                 None
4121                                         };
4122                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4123                                         next_msgs = new_next_msgs;
4124                                 }
4125                         }
4126                 }
4127
4128                 let mut prev_node = expected_route.last().unwrap();
4129                 for (idx, node) in expected_route.iter().rev().enumerate() {
4130                         assert_eq!(expected_next_node, node.node.get_our_node_id());
4131                         let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
4132                         if next_msgs.is_some() {
4133                                 mid_update_fulfill_dance!(node, prev_node, update_next_msgs);
4134                         } else if update_next_msgs {
4135                                 next_msgs = get_next_msgs!(node);
4136                         } else {
4137                                 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
4138                         }
4139                         if !skip_last && idx == expected_route.len() - 1 {
4140                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4141                         }
4142
4143                         prev_node = node;
4144                 }
4145
4146                 if !skip_last {
4147                         last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
4148                         let events = origin_node.node.get_and_clear_pending_events();
4149                         assert_eq!(events.len(), 1);
4150                         match events[0] {
4151                                 Event::PaymentSent { payment_preimage } => {
4152                                         assert_eq!(payment_preimage, our_payment_preimage);
4153                                 },
4154                                 _ => panic!("Unexpected event"),
4155                         }
4156                 }
4157         }
4158
4159         fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: PaymentPreimage) {
4160                 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage);
4161         }
4162
4163         const TEST_FINAL_CLTV: u32 = 32;
4164
4165         fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
4166                 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();
4167                 assert_eq!(route.hops.len(), expected_route.len());
4168                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4169                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
4170                 }
4171
4172                 send_along_route(origin_node, route, expected_route, recv_value)
4173         }
4174
4175         fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
4176                 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();
4177                 assert_eq!(route.hops.len(), expected_route.len());
4178                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4179                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
4180                 }
4181
4182                 let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4183
4184                 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
4185                 match err {
4186                         APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
4187                         _ => panic!("Unknown error variants"),
4188                 };
4189         }
4190
4191         fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
4192                 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
4193                 claim_payment(&origin, expected_route, our_payment_preimage);
4194         }
4195
4196         fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: PaymentHash) {
4197                 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash, 0));
4198                 check_added_monitors!(expected_route.last().unwrap(), 1);
4199
4200                 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
4201                 macro_rules! update_fail_dance {
4202                         ($node: expr, $prev_node: expr, $last_node: expr) => {
4203                                 {
4204                                         $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4205                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
4206                                 }
4207                         }
4208                 }
4209
4210                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4211                 let mut prev_node = expected_route.last().unwrap();
4212                 for (idx, node) in expected_route.iter().rev().enumerate() {
4213                         assert_eq!(expected_next_node, node.node.get_our_node_id());
4214                         if next_msgs.is_some() {
4215                                 // We may be the "last node" for the purpose of the commitment dance if we're
4216                                 // skipping the last node (implying it is disconnected) and we're the
4217                                 // second-to-last node!
4218                                 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
4219                         }
4220
4221                         let events = node.node.get_and_clear_pending_msg_events();
4222                         if !skip_last || idx != expected_route.len() - 1 {
4223                                 assert_eq!(events.len(), 1);
4224                                 match events[0] {
4225                                         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 } } => {
4226                                                 assert!(update_add_htlcs.is_empty());
4227                                                 assert!(update_fulfill_htlcs.is_empty());
4228                                                 assert_eq!(update_fail_htlcs.len(), 1);
4229                                                 assert!(update_fail_malformed_htlcs.is_empty());
4230                                                 assert!(update_fee.is_none());
4231                                                 expected_next_node = node_id.clone();
4232                                                 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
4233                                         },
4234                                         _ => panic!("Unexpected event"),
4235                                 }
4236                         } else {
4237                                 assert!(events.is_empty());
4238                         }
4239                         if !skip_last && idx == expected_route.len() - 1 {
4240                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4241                         }
4242
4243                         prev_node = node;
4244                 }
4245
4246                 if !skip_last {
4247                         update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
4248
4249                         let events = origin_node.node.get_and_clear_pending_events();
4250                         assert_eq!(events.len(), 1);
4251                         match events[0] {
4252                                 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
4253                                         assert_eq!(payment_hash, our_payment_hash);
4254                                         assert!(rejected_by_dest);
4255                                 },
4256                                 _ => panic!("Unexpected event"),
4257                         }
4258                 }
4259         }
4260
4261         fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: PaymentHash) {
4262                 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
4263         }
4264
4265         fn create_network(node_count: usize) -> Vec<Node> {
4266                 let mut nodes = Vec::new();
4267                 let mut rng = thread_rng();
4268                 let secp_ctx = Secp256k1::new();
4269
4270                 let chan_count = Rc::new(RefCell::new(0));
4271                 let payment_count = Rc::new(RefCell::new(0));
4272
4273                 for i in 0..node_count {
4274                         let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
4275                         let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
4276                         let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
4277                         let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
4278                         let mut seed = [0; 32];
4279                         rng.fill_bytes(&mut seed);
4280                         let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&seed, Network::Testnet, Arc::clone(&logger)));
4281                         let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone()));
4282                         let mut config = UserConfig::new();
4283                         config.channel_options.announced_channel = true;
4284                         config.channel_limits.force_announced_channel_preference = false;
4285                         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();
4286                         let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), chain_monitor.clone(), Arc::clone(&logger));
4287                         nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router, keys_manager, node_seed: seed,
4288                                 network_payment_count: payment_count.clone(),
4289                                 network_chan_count: chan_count.clone(),
4290                         });
4291                 }
4292
4293                 nodes
4294         }
4295
4296         #[test]
4297         fn test_async_inbound_update_fee() {
4298                 let mut nodes = create_network(2);
4299                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4300                 let channel_id = chan.2;
4301
4302                 // balancing
4303                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4304
4305                 // A                                        B
4306                 // update_fee                            ->
4307                 // send (1) commitment_signed            -.
4308                 //                                       <- update_add_htlc/commitment_signed
4309                 // send (2) RAA (awaiting remote revoke) -.
4310                 // (1) commitment_signed is delivered    ->
4311                 //                                       .- send (3) RAA (awaiting remote revoke)
4312                 // (2) RAA is delivered                  ->
4313                 //                                       .- send (4) commitment_signed
4314                 //                                       <- (3) RAA is delivered
4315                 // send (5) commitment_signed            -.
4316                 //                                       <- (4) commitment_signed is delivered
4317                 // send (6) RAA                          -.
4318                 // (5) commitment_signed is delivered    ->
4319                 //                                       <- RAA
4320                 // (6) RAA is delivered                  ->
4321
4322                 // First nodes[0] generates an update_fee
4323                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4324                 check_added_monitors!(nodes[0], 1);
4325
4326                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4327                 assert_eq!(events_0.len(), 1);
4328                 let (update_msg, commitment_signed) = match events_0[0] { // (1)
4329                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4330                                 (update_fee.as_ref(), commitment_signed)
4331                         },
4332                         _ => panic!("Unexpected event"),
4333                 };
4334
4335                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4336
4337                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4338                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4339                 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();
4340                 check_added_monitors!(nodes[1], 1);
4341
4342                 let payment_event = {
4343                         let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4344                         assert_eq!(events_1.len(), 1);
4345                         SendEvent::from_event(events_1.remove(0))
4346                 };
4347                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4348                 assert_eq!(payment_event.msgs.len(), 1);
4349
4350                 // ...now when the messages get delivered everyone should be happy
4351                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4352                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4353                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4354                 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4355                 check_added_monitors!(nodes[0], 1);
4356
4357                 // deliver(1), generate (3):
4358                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4359                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4360                 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
4361                 check_added_monitors!(nodes[1], 1);
4362
4363                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap(); // deliver (2)
4364                 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4365                 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
4366                 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
4367                 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
4368                 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
4369                 assert!(bs_update.update_fee.is_none()); // (4)
4370                 check_added_monitors!(nodes[1], 1);
4371
4372                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap(); // deliver (3)
4373                 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4374                 assert!(as_update.update_add_htlcs.is_empty()); // (5)
4375                 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
4376                 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
4377                 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
4378                 assert!(as_update.update_fee.is_none()); // (5)
4379                 check_added_monitors!(nodes[0], 1);
4380
4381                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed).unwrap(); // deliver (4)
4382                 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4383                 // only (6) so get_event_msg's assert(len == 1) passes
4384                 check_added_monitors!(nodes[0], 1);
4385
4386                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed).unwrap(); // deliver (5)
4387                 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4388                 check_added_monitors!(nodes[1], 1);
4389
4390                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4391                 check_added_monitors!(nodes[0], 1);
4392
4393                 let events_2 = nodes[0].node.get_and_clear_pending_events();
4394                 assert_eq!(events_2.len(), 1);
4395                 match events_2[0] {
4396                         Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
4397                         _ => panic!("Unexpected event"),
4398                 }
4399
4400                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap(); // deliver (6)
4401                 check_added_monitors!(nodes[1], 1);
4402         }
4403
4404         #[test]
4405         fn test_update_fee_unordered_raa() {
4406                 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
4407                 // crash in an earlier version of the update_fee patch)
4408                 let mut nodes = create_network(2);
4409                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4410                 let channel_id = chan.2;
4411
4412                 // balancing
4413                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4414
4415                 // First nodes[0] generates an update_fee
4416                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4417                 check_added_monitors!(nodes[0], 1);
4418
4419                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4420                 assert_eq!(events_0.len(), 1);
4421                 let update_msg = match events_0[0] { // (1)
4422                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
4423                                 update_fee.as_ref()
4424                         },
4425                         _ => panic!("Unexpected event"),
4426                 };
4427
4428                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4429
4430                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4431                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4432                 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();
4433                 check_added_monitors!(nodes[1], 1);
4434
4435                 let payment_event = {
4436                         let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4437                         assert_eq!(events_1.len(), 1);
4438                         SendEvent::from_event(events_1.remove(0))
4439                 };
4440                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4441                 assert_eq!(payment_event.msgs.len(), 1);
4442
4443                 // ...now when the messages get delivered everyone should be happy
4444                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4445                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4446                 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4447                 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4448                 check_added_monitors!(nodes[0], 1);
4449
4450                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap(); // deliver (2)
4451                 check_added_monitors!(nodes[1], 1);
4452
4453                 // We can't continue, sadly, because our (1) now has a bogus signature
4454         }
4455
4456         #[test]
4457         fn test_multi_flight_update_fee() {
4458                 let nodes = create_network(2);
4459                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4460                 let channel_id = chan.2;
4461
4462                 // A                                        B
4463                 // update_fee/commitment_signed          ->
4464                 //                                       .- send (1) RAA and (2) commitment_signed
4465                 // update_fee (never committed)          ->
4466                 // (3) update_fee                        ->
4467                 // We have to manually generate the above update_fee, it is allowed by the protocol but we
4468                 // don't track which updates correspond to which revoke_and_ack responses so we're in
4469                 // AwaitingRAA mode and will not generate the update_fee yet.
4470                 //                                       <- (1) RAA delivered
4471                 // (3) is generated and send (4) CS      -.
4472                 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
4473                 // know the per_commitment_point to use for it.
4474                 //                                       <- (2) commitment_signed delivered
4475                 // revoke_and_ack                        ->
4476                 //                                          B should send no response here
4477                 // (4) commitment_signed delivered       ->
4478                 //                                       <- RAA/commitment_signed delivered
4479                 // revoke_and_ack                        ->
4480
4481                 // First nodes[0] generates an update_fee
4482                 let initial_feerate = get_feerate!(nodes[0], channel_id);
4483                 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
4484                 check_added_monitors!(nodes[0], 1);
4485
4486                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4487                 assert_eq!(events_0.len(), 1);
4488                 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
4489                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4490                                 (update_fee.as_ref().unwrap(), commitment_signed)
4491                         },
4492                         _ => panic!("Unexpected event"),
4493                 };
4494
4495                 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
4496                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1).unwrap();
4497                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1).unwrap();
4498                 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4499                 check_added_monitors!(nodes[1], 1);
4500
4501                 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
4502                 // transaction:
4503                 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
4504                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4505                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4506
4507                 // Create the (3) update_fee message that nodes[0] will generate before it does...
4508                 let mut update_msg_2 = msgs::UpdateFee {
4509                         channel_id: update_msg_1.channel_id.clone(),
4510                         feerate_per_kw: (initial_feerate + 30) as u32,
4511                 };
4512
4513                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4514
4515                 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
4516                 // Deliver (3)
4517                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4518
4519                 // Deliver (1), generating (3) and (4)
4520                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap();
4521                 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4522                 check_added_monitors!(nodes[0], 1);
4523                 assert!(as_second_update.update_add_htlcs.is_empty());
4524                 assert!(as_second_update.update_fulfill_htlcs.is_empty());
4525                 assert!(as_second_update.update_fail_htlcs.is_empty());
4526                 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
4527                 // Check that the update_fee newly generated matches what we delivered:
4528                 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
4529                 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
4530
4531                 // Deliver (2) commitment_signed
4532                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
4533                 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4534                 check_added_monitors!(nodes[0], 1);
4535                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4536
4537                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap();
4538                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4539                 check_added_monitors!(nodes[1], 1);
4540
4541                 // Delever (4)
4542                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed).unwrap();
4543                 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4544                 check_added_monitors!(nodes[1], 1);
4545
4546                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4547                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4548                 check_added_monitors!(nodes[0], 1);
4549
4550                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment).unwrap();
4551                 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4552                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4553                 check_added_monitors!(nodes[0], 1);
4554
4555                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap();
4556                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4557                 check_added_monitors!(nodes[1], 1);
4558         }
4559
4560         #[test]
4561         fn test_update_fee_vanilla() {
4562                 let nodes = create_network(2);
4563                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4564                 let channel_id = chan.2;
4565
4566                 let feerate = get_feerate!(nodes[0], channel_id);
4567                 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
4568                 check_added_monitors!(nodes[0], 1);
4569
4570                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4571                 assert_eq!(events_0.len(), 1);
4572                 let (update_msg, commitment_signed) = match events_0[0] {
4573                                 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 } } => {
4574                                 (update_fee.as_ref(), commitment_signed)
4575                         },
4576                         _ => panic!("Unexpected event"),
4577                 };
4578                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4579
4580                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4581                 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4582                 check_added_monitors!(nodes[1], 1);
4583
4584                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4585                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4586                 check_added_monitors!(nodes[0], 1);
4587
4588                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4589                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4590                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4591                 check_added_monitors!(nodes[0], 1);
4592
4593                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4594                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4595                 check_added_monitors!(nodes[1], 1);
4596         }
4597
4598         #[test]
4599         fn test_update_fee_that_funder_cannot_afford() {
4600                 let nodes = create_network(2);
4601                 let channel_value = 1888;
4602                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000);
4603                 let channel_id = chan.2;
4604
4605                 let feerate = 260;
4606                 nodes[0].node.update_fee(channel_id, feerate).unwrap();
4607                 check_added_monitors!(nodes[0], 1);
4608                 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4609
4610                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap()).unwrap();
4611
4612                 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
4613
4614                 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
4615                 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
4616                 {
4617                         let chan_lock = nodes[1].node.channel_state.lock().unwrap();
4618                         let chan = chan_lock.by_id.get(&channel_id).unwrap();
4619
4620                         //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
4621                         let num_htlcs = chan.last_local_commitment_txn[0].output.len() - 2;
4622                         let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
4623                         let mut actual_fee = chan.last_local_commitment_txn[0].output.iter().fold(0, |acc, output| acc + output.value);
4624                         actual_fee = channel_value - actual_fee;
4625                         assert_eq!(total_fee, actual_fee);
4626                 } //drop the mutex
4627
4628                 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
4629                 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
4630                 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
4631                 check_added_monitors!(nodes[0], 1);
4632
4633                 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4634
4635                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap()).unwrap();
4636
4637                 //While producing the commitment_signed response after handling a received update_fee request the
4638                 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
4639                 //Should produce and error.
4640                 let err = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed).unwrap_err();
4641
4642                 assert!(match err.err {
4643                         "Funding remote cannot afford proposed new fee" => true,
4644                         _ => false,
4645                 });
4646
4647                 //clear the message we could not handle
4648                 nodes[1].node.get_and_clear_pending_msg_events();
4649         }
4650
4651         #[test]
4652         fn test_update_fee_with_fundee_update_add_htlc() {
4653                 let mut nodes = create_network(2);
4654                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4655                 let channel_id = chan.2;
4656
4657                 // balancing
4658                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4659
4660                 let feerate = get_feerate!(nodes[0], channel_id);
4661                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4662                 check_added_monitors!(nodes[0], 1);
4663
4664                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4665                 assert_eq!(events_0.len(), 1);
4666                 let (update_msg, commitment_signed) = match events_0[0] {
4667                                 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 } } => {
4668                                 (update_fee.as_ref(), commitment_signed)
4669                         },
4670                         _ => panic!("Unexpected event"),
4671                 };
4672                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4673                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4674                 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4675                 check_added_monitors!(nodes[1], 1);
4676
4677                 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
4678
4679                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
4680
4681                 // nothing happens since node[1] is in AwaitingRemoteRevoke
4682                 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
4683                 {
4684                         let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
4685                         assert_eq!(added_monitors.len(), 0);
4686                         added_monitors.clear();
4687                 }
4688                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4689                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4690                 // node[1] has nothing to do
4691
4692                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4693                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4694                 check_added_monitors!(nodes[0], 1);
4695
4696                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4697                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4698                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4699                 check_added_monitors!(nodes[0], 1);
4700                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4701                 check_added_monitors!(nodes[1], 1);
4702                 // AwaitingRemoteRevoke ends here
4703
4704                 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4705                 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
4706                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
4707                 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
4708                 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
4709                 assert_eq!(commitment_update.update_fee.is_none(), true);
4710
4711                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]).unwrap();
4712                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4713                 check_added_monitors!(nodes[0], 1);
4714                 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4715
4716                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke).unwrap();
4717                 check_added_monitors!(nodes[1], 1);
4718                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4719
4720                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed).unwrap();
4721                 check_added_monitors!(nodes[1], 1);
4722                 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4723                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4724
4725                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke).unwrap();
4726                 check_added_monitors!(nodes[0], 1);
4727                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4728
4729                 let events = nodes[0].node.get_and_clear_pending_events();
4730                 assert_eq!(events.len(), 1);
4731                 match events[0] {
4732                         Event::PendingHTLCsForwardable { .. } => { },
4733                         _ => panic!("Unexpected event"),
4734                 };
4735                 nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
4736                 nodes[0].node.process_pending_htlc_forwards();
4737
4738                 let events = nodes[0].node.get_and_clear_pending_events();
4739                 assert_eq!(events.len(), 1);
4740                 match events[0] {
4741                         Event::PaymentReceived { .. } => { },
4742                         _ => panic!("Unexpected event"),
4743                 };
4744
4745                 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
4746
4747                 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
4748                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
4749                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4750         }
4751
4752         #[test]
4753         fn test_update_fee() {
4754                 let nodes = create_network(2);
4755                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4756                 let channel_id = chan.2;
4757
4758                 // A                                        B
4759                 // (1) update_fee/commitment_signed      ->
4760                 //                                       <- (2) revoke_and_ack
4761                 //                                       .- send (3) commitment_signed
4762                 // (4) update_fee/commitment_signed      ->
4763                 //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
4764                 //                                       <- (3) commitment_signed delivered
4765                 // send (6) revoke_and_ack               -.
4766                 //                                       <- (5) deliver revoke_and_ack
4767                 // (6) deliver revoke_and_ack            ->
4768                 //                                       .- send (7) commitment_signed in response to (4)
4769                 //                                       <- (7) deliver commitment_signed
4770                 // revoke_and_ack                        ->
4771
4772                 // Create and deliver (1)...
4773                 let feerate = get_feerate!(nodes[0], channel_id);
4774                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4775                 check_added_monitors!(nodes[0], 1);
4776
4777                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4778                 assert_eq!(events_0.len(), 1);
4779                 let (update_msg, commitment_signed) = match events_0[0] {
4780                                 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 } } => {
4781                                 (update_fee.as_ref(), commitment_signed)
4782                         },
4783                         _ => panic!("Unexpected event"),
4784                 };
4785                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4786
4787                 // Generate (2) and (3):
4788                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4789                 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4790                 check_added_monitors!(nodes[1], 1);
4791
4792                 // Deliver (2):
4793                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4794                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4795                 check_added_monitors!(nodes[0], 1);
4796
4797                 // Create and deliver (4)...
4798                 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
4799                 check_added_monitors!(nodes[0], 1);
4800                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4801                 assert_eq!(events_0.len(), 1);
4802                 let (update_msg, commitment_signed) = match events_0[0] {
4803                                 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 } } => {
4804                                 (update_fee.as_ref(), commitment_signed)
4805                         },
4806                         _ => panic!("Unexpected event"),
4807                 };
4808
4809                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4810                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4811                 check_added_monitors!(nodes[1], 1);
4812                 // ... creating (5)
4813                 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4814                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4815
4816                 // Handle (3), creating (6):
4817                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0).unwrap();
4818                 check_added_monitors!(nodes[0], 1);
4819                 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4820                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4821
4822                 // Deliver (5):
4823                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4824                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4825                 check_added_monitors!(nodes[0], 1);
4826
4827                 // Deliver (6), creating (7):
4828                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0).unwrap();
4829                 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4830                 assert!(commitment_update.update_add_htlcs.is_empty());
4831                 assert!(commitment_update.update_fulfill_htlcs.is_empty());
4832                 assert!(commitment_update.update_fail_htlcs.is_empty());
4833                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
4834                 assert!(commitment_update.update_fee.is_none());
4835                 check_added_monitors!(nodes[1], 1);
4836
4837                 // Deliver (7)
4838                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4839                 check_added_monitors!(nodes[0], 1);
4840                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4841                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4842
4843                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4844                 check_added_monitors!(nodes[1], 1);
4845                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4846
4847                 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
4848                 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
4849                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4850         }
4851
4852         #[test]
4853         fn pre_funding_lock_shutdown_test() {
4854                 // Test sending a shutdown prior to funding_locked after funding generation
4855                 let nodes = create_network(2);
4856                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0);
4857                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4858                 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4859                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4860
4861                 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
4862                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4863                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4864                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4865                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4866
4867                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4868                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4869                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4870                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4871                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4872                 assert!(node_0_none.is_none());
4873
4874                 assert!(nodes[0].node.list_channels().is_empty());
4875                 assert!(nodes[1].node.list_channels().is_empty());
4876         }
4877
4878         #[test]
4879         fn updates_shutdown_wait() {
4880                 // Test sending a shutdown with outstanding updates pending
4881                 let mut nodes = create_network(3);
4882                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4883                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4884                 let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4885                 let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4886
4887                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
4888
4889                 nodes[0].node.close_channel(&chan_1.2).unwrap();
4890                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4891                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4892                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4893                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4894
4895                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4896                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4897
4898                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4899                 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route_1, payment_hash) {}
4900                 else { panic!("New sends should fail!") };
4901                 if let Err(APIError::ChannelUnavailable {..}) = nodes[1].node.send_payment(route_2, payment_hash) {}
4902                 else { panic!("New sends should fail!") };
4903
4904                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
4905                 check_added_monitors!(nodes[2], 1);
4906                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4907                 assert!(updates.update_add_htlcs.is_empty());
4908                 assert!(updates.update_fail_htlcs.is_empty());
4909                 assert!(updates.update_fail_malformed_htlcs.is_empty());
4910                 assert!(updates.update_fee.is_none());
4911                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4912                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
4913                 check_added_monitors!(nodes[1], 1);
4914                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4915                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
4916
4917                 assert!(updates_2.update_add_htlcs.is_empty());
4918                 assert!(updates_2.update_fail_htlcs.is_empty());
4919                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
4920                 assert!(updates_2.update_fee.is_none());
4921                 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
4922                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
4923                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
4924
4925                 let events = nodes[0].node.get_and_clear_pending_events();
4926                 assert_eq!(events.len(), 1);
4927                 match events[0] {
4928                         Event::PaymentSent { ref payment_preimage } => {
4929                                 assert_eq!(our_payment_preimage, *payment_preimage);
4930                         },
4931                         _ => panic!("Unexpected event"),
4932                 }
4933
4934                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4935                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4936                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4937                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4938                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4939                 assert!(node_0_none.is_none());
4940
4941                 assert!(nodes[0].node.list_channels().is_empty());
4942
4943                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4944                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
4945                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
4946                 assert!(nodes[1].node.list_channels().is_empty());
4947                 assert!(nodes[2].node.list_channels().is_empty());
4948         }
4949
4950         #[test]
4951         fn htlc_fail_async_shutdown() {
4952                 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
4953                 let mut nodes = create_network(3);
4954                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4955                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4956
4957                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4958                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4959                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
4960                 check_added_monitors!(nodes[0], 1);
4961                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4962                 assert_eq!(updates.update_add_htlcs.len(), 1);
4963                 assert!(updates.update_fulfill_htlcs.is_empty());
4964                 assert!(updates.update_fail_htlcs.is_empty());
4965                 assert!(updates.update_fail_malformed_htlcs.is_empty());
4966                 assert!(updates.update_fee.is_none());
4967
4968                 nodes[1].node.close_channel(&chan_1.2).unwrap();
4969                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4970                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4971                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4972
4973                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
4974                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
4975                 check_added_monitors!(nodes[1], 1);
4976                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4977                 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
4978
4979                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4980                 assert!(updates_2.update_add_htlcs.is_empty());
4981                 assert!(updates_2.update_fulfill_htlcs.is_empty());
4982                 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
4983                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
4984                 assert!(updates_2.update_fee.is_none());
4985
4986                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]).unwrap();
4987                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
4988
4989                 let events = nodes[0].node.get_and_clear_pending_events();
4990                 assert_eq!(events.len(), 1);
4991                 match events[0] {
4992                         Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } => {
4993                                 assert_eq!(our_payment_hash, *payment_hash);
4994                                 assert!(!rejected_by_dest);
4995                         },
4996                         _ => panic!("Unexpected event"),
4997                 }
4998
4999                 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5000                 assert_eq!(msg_events.len(), 2);
5001                 let node_0_closing_signed = match msg_events[0] {
5002                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
5003                                 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5004                                 (*msg).clone()
5005                         },
5006                         _ => panic!("Unexpected event"),
5007                 };
5008                 match msg_events[1] {
5009                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
5010                                 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
5011                         },
5012                         _ => panic!("Unexpected event"),
5013                 }
5014
5015                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5016                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5017                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5018                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5019                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5020                 assert!(node_0_none.is_none());
5021
5022                 assert!(nodes[0].node.list_channels().is_empty());
5023
5024                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5025                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5026                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5027                 assert!(nodes[1].node.list_channels().is_empty());
5028                 assert!(nodes[2].node.list_channels().is_empty());
5029         }
5030
5031         fn do_test_shutdown_rebroadcast(recv_count: u8) {
5032                 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
5033                 // messages delivered prior to disconnect
5034                 let nodes = create_network(3);
5035                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5036                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5037
5038                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
5039
5040                 nodes[1].node.close_channel(&chan_1.2).unwrap();
5041                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5042                 if recv_count > 0 {
5043                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
5044                         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5045                         if recv_count > 1 {
5046                                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
5047                         }
5048                 }
5049
5050                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5051                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5052
5053                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5054                 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5055                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5056                 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5057
5058                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish).unwrap();
5059                 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5060                 assert!(node_1_shutdown == node_1_2nd_shutdown);
5061
5062                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish).unwrap();
5063                 let node_0_2nd_shutdown = if recv_count > 0 {
5064                         let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5065                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5066                         node_0_2nd_shutdown
5067                 } else {
5068                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5069                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5070                         get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
5071                 };
5072                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown).unwrap();
5073
5074                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5075                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5076
5077                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
5078                 check_added_monitors!(nodes[2], 1);
5079                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5080                 assert!(updates.update_add_htlcs.is_empty());
5081                 assert!(updates.update_fail_htlcs.is_empty());
5082                 assert!(updates.update_fail_malformed_htlcs.is_empty());
5083                 assert!(updates.update_fee.is_none());
5084                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5085                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
5086                 check_added_monitors!(nodes[1], 1);
5087                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5088                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
5089
5090                 assert!(updates_2.update_add_htlcs.is_empty());
5091                 assert!(updates_2.update_fail_htlcs.is_empty());
5092                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
5093                 assert!(updates_2.update_fee.is_none());
5094                 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
5095                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
5096                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
5097
5098                 let events = nodes[0].node.get_and_clear_pending_events();
5099                 assert_eq!(events.len(), 1);
5100                 match events[0] {
5101                         Event::PaymentSent { ref payment_preimage } => {
5102                                 assert_eq!(our_payment_preimage, *payment_preimage);
5103                         },
5104                         _ => panic!("Unexpected event"),
5105                 }
5106
5107                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5108                 if recv_count > 0 {
5109                         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5110                         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5111                         assert!(node_1_closing_signed.is_some());
5112                 }
5113
5114                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5115                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5116
5117                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5118                 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5119                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5120                 if recv_count == 0 {
5121                         // If all closing_signeds weren't delivered we can just resume where we left off...
5122                         let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5123
5124                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish).unwrap();
5125                         let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5126                         assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
5127
5128                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish).unwrap();
5129                         let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5130                         assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
5131
5132                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown).unwrap();
5133                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5134
5135                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown).unwrap();
5136                         let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5137                         assert!(node_0_closing_signed == node_0_2nd_closing_signed);
5138
5139                         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed).unwrap();
5140                         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5141                         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5142                         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5143                         assert!(node_0_none.is_none());
5144                 } else {
5145                         // If one node, however, received + responded with an identical closing_signed we end
5146                         // up erroring and node[0] will try to broadcast its own latest commitment transaction.
5147                         // There isn't really anything better we can do simply, but in the future we might
5148                         // explore storing a set of recently-closed channels that got disconnected during
5149                         // closing_signed and avoiding broadcasting local commitment txn for some timeout to
5150                         // give our counterparty enough time to (potentially) broadcast a cooperative closing
5151                         // transaction.
5152                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5153
5154                         if let Err(msgs::HandleError{action: Some(msgs::ErrorAction::SendErrorMessage{msg}), ..}) =
5155                                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish) {
5156                                 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
5157                                 let msgs::ErrorMessage {ref channel_id, ..} = msg;
5158                                 assert_eq!(*channel_id, chan_1.2);
5159                         } else { panic!("Needed SendErrorMessage close"); }
5160
5161                         // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
5162                         // checks it, but in this case nodes[0] didn't ever get a chance to receive a
5163                         // closing_signed so we do it ourselves
5164                         let events = nodes[0].node.get_and_clear_pending_msg_events();
5165                         assert_eq!(events.len(), 1);
5166                         match events[0] {
5167                                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5168                                         assert_eq!(msg.contents.flags & 2, 2);
5169                                 },
5170                                 _ => panic!("Unexpected event"),
5171                         }
5172                 }
5173
5174                 assert!(nodes[0].node.list_channels().is_empty());
5175
5176                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5177                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5178                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5179                 assert!(nodes[1].node.list_channels().is_empty());
5180                 assert!(nodes[2].node.list_channels().is_empty());
5181         }
5182
5183         #[test]
5184         fn test_shutdown_rebroadcast() {
5185                 do_test_shutdown_rebroadcast(0);
5186                 do_test_shutdown_rebroadcast(1);
5187                 do_test_shutdown_rebroadcast(2);
5188         }
5189
5190         #[test]
5191         fn fake_network_test() {
5192                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5193                 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
5194                 let nodes = create_network(4);
5195
5196                 // Create some initial channels
5197                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5198                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5199                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5200
5201                 // Rebalance the network a bit by relaying one payment through all the channels...
5202                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5203                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5204                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5205                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5206
5207                 // Send some more payments
5208                 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
5209                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
5210                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
5211
5212                 // Test failure packets
5213                 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
5214                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
5215
5216                 // Add a new channel that skips 3
5217                 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
5218
5219                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
5220                 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
5221                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5222                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5223                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5224                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5225                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5226
5227                 // Do some rebalance loop payments, simultaneously
5228                 let mut hops = Vec::with_capacity(3);
5229                 hops.push(RouteHop {
5230                         pubkey: nodes[2].node.get_our_node_id(),
5231                         short_channel_id: chan_2.0.contents.short_channel_id,
5232                         fee_msat: 0,
5233                         cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
5234                 });
5235                 hops.push(RouteHop {
5236                         pubkey: nodes[3].node.get_our_node_id(),
5237                         short_channel_id: chan_3.0.contents.short_channel_id,
5238                         fee_msat: 0,
5239                         cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
5240                 });
5241                 hops.push(RouteHop {
5242                         pubkey: nodes[1].node.get_our_node_id(),
5243                         short_channel_id: chan_4.0.contents.short_channel_id,
5244                         fee_msat: 1000000,
5245                         cltv_expiry_delta: TEST_FINAL_CLTV,
5246                 });
5247                 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;
5248                 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;
5249                 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
5250
5251                 let mut hops = Vec::with_capacity(3);
5252                 hops.push(RouteHop {
5253                         pubkey: nodes[3].node.get_our_node_id(),
5254                         short_channel_id: chan_4.0.contents.short_channel_id,
5255                         fee_msat: 0,
5256                         cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
5257                 });
5258                 hops.push(RouteHop {
5259                         pubkey: nodes[2].node.get_our_node_id(),
5260                         short_channel_id: chan_3.0.contents.short_channel_id,
5261                         fee_msat: 0,
5262                         cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
5263                 });
5264                 hops.push(RouteHop {
5265                         pubkey: nodes[1].node.get_our_node_id(),
5266                         short_channel_id: chan_2.0.contents.short_channel_id,
5267                         fee_msat: 1000000,
5268                         cltv_expiry_delta: TEST_FINAL_CLTV,
5269                 });
5270                 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;
5271                 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;
5272                 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
5273
5274                 // Claim the rebalances...
5275                 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
5276                 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
5277
5278                 // Add a duplicate new channel from 2 to 4
5279                 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3);
5280
5281                 // Send some payments across both channels
5282                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5283                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5284                 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5285
5286                 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
5287
5288                 //TODO: Test that routes work again here as we've been notified that the channel is full
5289
5290                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
5291                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
5292                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
5293
5294                 // Close down the channels...
5295                 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
5296                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
5297                 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
5298                 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
5299                 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
5300         }
5301
5302         #[test]
5303         fn duplicate_htlc_test() {
5304                 // Test that we accept duplicate payment_hash HTLCs across the network and that
5305                 // claiming/failing them are all separate and don't effect each other
5306                 let mut nodes = create_network(6);
5307
5308                 // Create some initial channels to route via 3 to 4/5 from 0/1/2
5309                 create_announced_chan_between_nodes(&nodes, 0, 3);
5310                 create_announced_chan_between_nodes(&nodes, 1, 3);
5311                 create_announced_chan_between_nodes(&nodes, 2, 3);
5312                 create_announced_chan_between_nodes(&nodes, 3, 4);
5313                 create_announced_chan_between_nodes(&nodes, 3, 5);
5314
5315                 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
5316
5317                 *nodes[0].network_payment_count.borrow_mut() -= 1;
5318                 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
5319
5320                 *nodes[0].network_payment_count.borrow_mut() -= 1;
5321                 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
5322
5323                 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
5324                 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
5325                 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
5326         }
5327
5328         #[derive(PartialEq)]
5329         enum HTLCType { NONE, TIMEOUT, SUCCESS }
5330         /// Tests that the given node has broadcast transactions for the given Channel
5331         ///
5332         /// First checks that the latest local commitment tx has been broadcast, unless an explicit
5333         /// commitment_tx is provided, which may be used to test that a remote commitment tx was
5334         /// broadcast and the revoked outputs were claimed.
5335         ///
5336         /// Next tests that there is (or is not) a transaction that spends the commitment transaction
5337         /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
5338         ///
5339         /// All broadcast transactions must be accounted for in one of the above three types of we'll
5340         /// also fail.
5341         fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
5342                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5343                 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
5344
5345                 let mut res = Vec::with_capacity(2);
5346                 node_txn.retain(|tx| {
5347                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
5348                                 check_spends!(tx, chan.3.clone());
5349                                 if commitment_tx.is_none() {
5350                                         res.push(tx.clone());
5351                                 }
5352                                 false
5353                         } else { true }
5354                 });
5355                 if let Some(explicit_tx) = commitment_tx {
5356                         res.push(explicit_tx.clone());
5357                 }
5358
5359                 assert_eq!(res.len(), 1);
5360
5361                 if has_htlc_tx != HTLCType::NONE {
5362                         node_txn.retain(|tx| {
5363                                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
5364                                         check_spends!(tx, res[0].clone());
5365                                         if has_htlc_tx == HTLCType::TIMEOUT {
5366                                                 assert!(tx.lock_time != 0);
5367                                         } else {
5368                                                 assert!(tx.lock_time == 0);
5369                                         }
5370                                         res.push(tx.clone());
5371                                         false
5372                                 } else { true }
5373                         });
5374                         assert!(res.len() == 2 || res.len() == 3);
5375                         if res.len() == 3 {
5376                                 assert_eq!(res[1], res[2]);
5377                         }
5378                 }
5379
5380                 assert!(node_txn.is_empty());
5381                 res
5382         }
5383
5384         /// Tests that the given node has broadcast a claim transaction against the provided revoked
5385         /// HTLC transaction.
5386         fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
5387                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5388                 assert_eq!(node_txn.len(), 1);
5389                 node_txn.retain(|tx| {
5390                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
5391                                 check_spends!(tx, revoked_tx.clone());
5392                                 false
5393                         } else { true }
5394                 });
5395                 assert!(node_txn.is_empty());
5396         }
5397
5398         fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
5399                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5400
5401                 assert!(node_txn.len() >= 1);
5402                 assert_eq!(node_txn[0].input.len(), 1);
5403                 let mut found_prev = false;
5404
5405                 for tx in prev_txn {
5406                         if node_txn[0].input[0].previous_output.txid == tx.txid() {
5407                                 check_spends!(node_txn[0], tx.clone());
5408                                 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
5409                                 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
5410
5411                                 found_prev = true;
5412                                 break;
5413                         }
5414                 }
5415                 assert!(found_prev);
5416
5417                 let mut res = Vec::new();
5418                 mem::swap(&mut *node_txn, &mut res);
5419                 res
5420         }
5421
5422         fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
5423                 let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
5424                 assert_eq!(events_1.len(), 1);
5425                 let as_update = match events_1[0] {
5426                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5427                                 msg.clone()
5428                         },
5429                         _ => panic!("Unexpected event"),
5430                 };
5431
5432                 let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
5433                 assert_eq!(events_2.len(), 1);
5434                 let bs_update = match events_2[0] {
5435                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5436                                 msg.clone()
5437                         },
5438                         _ => panic!("Unexpected event"),
5439                 };
5440
5441                 for node in nodes {
5442                         node.router.handle_channel_update(&as_update).unwrap();
5443                         node.router.handle_channel_update(&bs_update).unwrap();
5444                 }
5445         }
5446
5447         macro_rules! expect_pending_htlcs_forwardable {
5448                 ($node: expr) => {{
5449                         let events = $node.node.get_and_clear_pending_events();
5450                         assert_eq!(events.len(), 1);
5451                         match events[0] {
5452                                 Event::PendingHTLCsForwardable { .. } => { },
5453                                 _ => panic!("Unexpected event"),
5454                         };
5455                         $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
5456                         $node.node.process_pending_htlc_forwards();
5457                 }}
5458         }
5459
5460         fn do_channel_reserve_test(test_recv: bool) {
5461                 use util::rng;
5462                 use std::sync::atomic::Ordering;
5463                 use ln::msgs::HandleError;
5464
5465                 macro_rules! get_channel_value_stat {
5466                         ($node: expr, $channel_id: expr) => {{
5467                                 let chan_lock = $node.node.channel_state.lock().unwrap();
5468                                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
5469                                 chan.get_value_stat()
5470                         }}
5471                 }
5472
5473                 let mut nodes = create_network(3);
5474                 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001);
5475                 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001);
5476
5477                 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
5478                 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
5479
5480                 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
5481                 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
5482
5483                 macro_rules! get_route_and_payment_hash {
5484                         ($recv_value: expr) => {{
5485                                 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
5486                                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5487                                 (route, payment_hash, payment_preimage)
5488                         }}
5489                 };
5490
5491                 macro_rules! expect_forward {
5492                         ($node: expr) => {{
5493                                 let mut events = $node.node.get_and_clear_pending_msg_events();
5494                                 assert_eq!(events.len(), 1);
5495                                 check_added_monitors!($node, 1);
5496                                 let payment_event = SendEvent::from_event(events.remove(0));
5497                                 payment_event
5498                         }}
5499                 }
5500
5501                 macro_rules! expect_payment_received {
5502                         ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
5503                                 let events = $node.node.get_and_clear_pending_events();
5504                                 assert_eq!(events.len(), 1);
5505                                 match events[0] {
5506                                         Event::PaymentReceived { ref payment_hash, amt } => {
5507                                                 assert_eq!($expected_payment_hash, *payment_hash);
5508                                                 assert_eq!($expected_recv_value, amt);
5509                                         },
5510                                         _ => panic!("Unexpected event"),
5511                                 }
5512                         }
5513                 };
5514
5515                 let feemsat = 239; // somehow we know?
5516                 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
5517
5518                 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
5519
5520                 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
5521                 {
5522                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
5523                         assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
5524                         let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
5525                         match err {
5526                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
5527                                 _ => panic!("Unknown error variants"),
5528                         }
5529                 }
5530
5531                 let mut htlc_id = 0;
5532                 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
5533                 // nodes[0]'s wealth
5534                 loop {
5535                         let amt_msat = recv_value_0 + total_fee_msat;
5536                         if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
5537                                 break;
5538                         }
5539                         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
5540                         htlc_id += 1;
5541
5542                         let (stat01_, stat11_, stat12_, stat22_) = (
5543                                 get_channel_value_stat!(nodes[0], chan_1.2),
5544                                 get_channel_value_stat!(nodes[1], chan_1.2),
5545                                 get_channel_value_stat!(nodes[1], chan_2.2),
5546                                 get_channel_value_stat!(nodes[2], chan_2.2),
5547                         );
5548
5549                         assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
5550                         assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
5551                         assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
5552                         assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
5553                         stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
5554                 }
5555
5556                 {
5557                         let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
5558                         // attempt to get channel_reserve violation
5559                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
5560                         let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
5561                         match err {
5562                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5563                                 _ => panic!("Unknown error variants"),
5564                         }
5565                 }
5566
5567                 // adding pending output
5568                 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
5569                 let amt_msat_1 = recv_value_1 + total_fee_msat;
5570
5571                 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
5572                 let payment_event_1 = {
5573                         nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
5574                         check_added_monitors!(nodes[0], 1);
5575
5576                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5577                         assert_eq!(events.len(), 1);
5578                         SendEvent::from_event(events.remove(0))
5579                 };
5580                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]).unwrap();
5581
5582                 // channel reserve test with htlc pending output > 0
5583                 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
5584                 {
5585                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5586                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5587                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5588                                 _ => panic!("Unknown error variants"),
5589                         }
5590                 }
5591
5592                 {
5593                         // test channel_reserve test on nodes[1] side
5594                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5595
5596                         // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
5597                         let secp_ctx = Secp256k1::new();
5598                         let session_priv = SecretKey::from_slice(&secp_ctx, &{
5599                                 let mut session_key = [0; 32];
5600                                 rng::fill_bytes(&mut session_key);
5601                                 session_key
5602                         }).expect("RNG is bad!");
5603
5604                         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5605                         let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
5606                         let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height).unwrap();
5607                         let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
5608                         let msg = msgs::UpdateAddHTLC {
5609                                 channel_id: chan_1.2,
5610                                 htlc_id,
5611                                 amount_msat: htlc_msat,
5612                                 payment_hash: our_payment_hash,
5613                                 cltv_expiry: htlc_cltv,
5614                                 onion_routing_packet: onion_packet,
5615                         };
5616
5617                         if test_recv {
5618                                 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).err().unwrap();
5619                                 match err {
5620                                         HandleError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
5621                                 }
5622                                 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
5623                                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5624                                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5625                                 let channel_close_broadcast = nodes[1].node.get_and_clear_pending_msg_events();
5626                                 assert_eq!(channel_close_broadcast.len(), 1);
5627                                 match channel_close_broadcast[0] {
5628                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5629                                                 assert_eq!(msg.contents.flags & 2, 2);
5630                                         },
5631                                         _ => panic!("Unexpected event"),
5632                                 }
5633                                 return;
5634                         }
5635                 }
5636
5637                 // split the rest to test holding cell
5638                 let recv_value_21 = recv_value_2/2;
5639                 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
5640                 {
5641                         let stat = get_channel_value_stat!(nodes[0], chan_1.2);
5642                         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);
5643                 }
5644
5645                 // now see if they go through on both sides
5646                 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
5647                 // but this will stuck in the holding cell
5648                 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
5649                 check_added_monitors!(nodes[0], 0);
5650                 let events = nodes[0].node.get_and_clear_pending_events();
5651                 assert_eq!(events.len(), 0);
5652
5653                 // test with outbound holding cell amount > 0
5654                 {
5655                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
5656                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5657                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5658                                 _ => panic!("Unknown error variants"),
5659                         }
5660                 }
5661
5662                 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
5663                 // this will also stuck in the holding cell
5664                 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
5665                 check_added_monitors!(nodes[0], 0);
5666                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
5667                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5668
5669                 // flush the pending htlc
5670                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg).unwrap();
5671                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5672                 check_added_monitors!(nodes[1], 1);
5673
5674                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
5675                 check_added_monitors!(nodes[0], 1);
5676                 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5677
5678                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed).unwrap();
5679                 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
5680                 // No commitment_signed so get_event_msg's assert(len == 1) passes
5681                 check_added_monitors!(nodes[0], 1);
5682
5683                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
5684                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5685                 check_added_monitors!(nodes[1], 1);
5686
5687                 expect_pending_htlcs_forwardable!(nodes[1]);
5688
5689                 let ref payment_event_11 = expect_forward!(nodes[1]);
5690                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]).unwrap();
5691                 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
5692
5693                 expect_pending_htlcs_forwardable!(nodes[2]);
5694                 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
5695
5696                 // flush the htlcs in the holding cell
5697                 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
5698                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]).unwrap();
5699                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]).unwrap();
5700                 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
5701                 expect_pending_htlcs_forwardable!(nodes[1]);
5702
5703                 let ref payment_event_3 = expect_forward!(nodes[1]);
5704                 assert_eq!(payment_event_3.msgs.len(), 2);
5705                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]).unwrap();
5706                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]).unwrap();
5707
5708                 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
5709                 expect_pending_htlcs_forwardable!(nodes[2]);
5710
5711                 let events = nodes[2].node.get_and_clear_pending_events();
5712                 assert_eq!(events.len(), 2);
5713                 match events[0] {
5714                         Event::PaymentReceived { ref payment_hash, amt } => {
5715                                 assert_eq!(our_payment_hash_21, *payment_hash);
5716                                 assert_eq!(recv_value_21, amt);
5717                         },
5718                         _ => panic!("Unexpected event"),
5719                 }
5720                 match events[1] {
5721                         Event::PaymentReceived { ref payment_hash, amt } => {
5722                                 assert_eq!(our_payment_hash_22, *payment_hash);
5723                                 assert_eq!(recv_value_22, amt);
5724                         },
5725                         _ => panic!("Unexpected event"),
5726                 }
5727
5728                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
5729                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
5730                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
5731
5732                 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);
5733                 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
5734                 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
5735                 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
5736
5737                 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
5738                 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
5739         }
5740
5741         #[test]
5742         fn channel_reserve_test() {
5743                 do_channel_reserve_test(false);
5744                 do_channel_reserve_test(true);
5745         }
5746
5747         #[test]
5748         fn channel_monitor_network_test() {
5749                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5750                 // tests that ChannelMonitor is able to recover from various states.
5751                 let nodes = create_network(5);
5752
5753                 // Create some initial channels
5754                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5755                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5756                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5757                 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5758
5759                 // Rebalance the network a bit by relaying one payment through all the channels...
5760                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5761                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5762                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5763                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5764
5765                 // Simple case with no pending HTLCs:
5766                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
5767                 {
5768                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
5769                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5770                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5771                         test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
5772                 }
5773                 get_announce_close_broadcast_events(&nodes, 0, 1);
5774                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5775                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5776
5777                 // One pending HTLC is discarded by the force-close:
5778                 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
5779
5780                 // Simple case of one pending HTLC to HTLC-Timeout
5781                 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
5782                 {
5783                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
5784                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5785                         nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5786                         test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
5787                 }
5788                 get_announce_close_broadcast_events(&nodes, 1, 2);
5789                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5790                 assert_eq!(nodes[2].node.list_channels().len(), 1);
5791
5792                 macro_rules! claim_funds {
5793                         ($node: expr, $prev_node: expr, $preimage: expr) => {
5794                                 {
5795                                         assert!($node.node.claim_funds($preimage));
5796                                         check_added_monitors!($node, 1);
5797
5798                                         let events = $node.node.get_and_clear_pending_msg_events();
5799                                         assert_eq!(events.len(), 1);
5800                                         match events[0] {
5801                                                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
5802                                                         assert!(update_add_htlcs.is_empty());
5803                                                         assert!(update_fail_htlcs.is_empty());
5804                                                         assert_eq!(*node_id, $prev_node.node.get_our_node_id());
5805                                                 },
5806                                                 _ => panic!("Unexpected event"),
5807                                         };
5808                                 }
5809                         }
5810                 }
5811
5812                 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
5813                 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
5814                 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
5815                 {
5816                         let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
5817
5818                         // Claim the payment on nodes[3], giving it knowledge of the preimage
5819                         claim_funds!(nodes[3], nodes[2], payment_preimage_1);
5820
5821                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5822                         nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
5823
5824                         check_preimage_claim(&nodes[3], &node_txn);
5825                 }
5826                 get_announce_close_broadcast_events(&nodes, 2, 3);
5827                 assert_eq!(nodes[2].node.list_channels().len(), 0);
5828                 assert_eq!(nodes[3].node.list_channels().len(), 1);
5829
5830                 { // Cheat and reset nodes[4]'s height to 1
5831                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5832                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![] }, 1);
5833                 }
5834
5835                 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
5836                 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
5837                 // One pending HTLC to time out:
5838                 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
5839                 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
5840                 // buffer space).
5841
5842                 {
5843                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5844                         nodes[3].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5845                         for i in 3..TEST_FINAL_CLTV + 2 + HTLC_FAIL_TIMEOUT_BLOCKS + 1 {
5846                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5847                                 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5848                         }
5849
5850                         let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
5851
5852                         // Claim the payment on nodes[4], giving it knowledge of the preimage
5853                         claim_funds!(nodes[4], nodes[3], payment_preimage_2);
5854
5855                         header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5856                         nodes[4].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5857                         for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
5858                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5859                                 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5860                         }
5861
5862                         test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
5863
5864                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5865                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
5866
5867                         check_preimage_claim(&nodes[4], &node_txn);
5868                 }
5869                 get_announce_close_broadcast_events(&nodes, 3, 4);
5870                 assert_eq!(nodes[3].node.list_channels().len(), 0);
5871                 assert_eq!(nodes[4].node.list_channels().len(), 0);
5872         }
5873
5874         #[test]
5875         fn test_justice_tx() {
5876                 // Test justice txn built on revoked HTLC-Success tx, against both sides
5877
5878                 let nodes = create_network(2);
5879                 // Create some new channels:
5880                 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
5881
5882                 // A pending HTLC which will be revoked:
5883                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5884                 // Get the will-be-revoked local txn from nodes[0]
5885                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5886                 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
5887                 assert_eq!(revoked_local_txn[0].input.len(), 1);
5888                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
5889                 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
5890                 assert_eq!(revoked_local_txn[1].input.len(), 1);
5891                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
5892                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
5893                 // Revoke the old state
5894                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
5895
5896                 {
5897                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5898                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5899                         {
5900                                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5901                                 assert_eq!(node_txn.len(), 3);
5902                                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5903                                 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
5904
5905                                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5906                                 node_txn.swap_remove(0);
5907                         }
5908                         test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
5909
5910                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5911                         let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
5912                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5913                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5914                         test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
5915                 }
5916                 get_announce_close_broadcast_events(&nodes, 0, 1);
5917
5918                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5919                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5920
5921                 // We test justice_tx build by A on B's revoked HTLC-Success tx
5922                 // Create some new channels:
5923                 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
5924
5925                 // A pending HTLC which will be revoked:
5926                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5927                 // Get the will-be-revoked local txn from B
5928                 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5929                 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
5930                 assert_eq!(revoked_local_txn[0].input.len(), 1);
5931                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
5932                 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
5933                 // Revoke the old state
5934                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
5935                 {
5936                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5937                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5938                         {
5939                                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5940                                 assert_eq!(node_txn.len(), 3);
5941                                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5942                                 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
5943
5944                                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5945                                 node_txn.swap_remove(0);
5946                         }
5947                         test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
5948
5949                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5950                         let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
5951                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5952                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5953                         test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone());
5954                 }
5955                 get_announce_close_broadcast_events(&nodes, 0, 1);
5956                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5957                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5958         }
5959
5960         #[test]
5961         fn revoked_output_claim() {
5962                 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
5963                 // transaction is broadcast by its counterparty
5964                 let nodes = create_network(2);
5965                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5966                 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
5967                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5968                 assert_eq!(revoked_local_txn.len(), 1);
5969                 // Only output is the full channel value back to nodes[0]:
5970                 assert_eq!(revoked_local_txn[0].output.len(), 1);
5971                 // Send a payment through, updating everyone's latest commitment txn
5972                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
5973
5974                 // Inform nodes[1] that nodes[0] broadcast a stale tx
5975                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5976                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5977                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5978                 assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
5979
5980                 assert_eq!(node_txn[0], node_txn[2]);
5981
5982                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5983                 check_spends!(node_txn[1], chan_1.3.clone());
5984
5985                 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
5986                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5987                 get_announce_close_broadcast_events(&nodes, 0, 1);
5988         }
5989
5990         #[test]
5991         fn claim_htlc_outputs_shared_tx() {
5992                 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
5993                 let nodes = create_network(2);
5994
5995                 // Create some new channel:
5996                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5997
5998                 // Rebalance the network to generate htlc in the two directions
5999                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6000                 // 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
6001                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6002                 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6003
6004                 // Get the will-be-revoked local txn from node[0]
6005                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6006                 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
6007                 assert_eq!(revoked_local_txn[0].input.len(), 1);
6008                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
6009                 assert_eq!(revoked_local_txn[1].input.len(), 1);
6010                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
6011                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
6012                 check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
6013
6014                 //Revoke the old state
6015                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6016
6017                 {
6018                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6019                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6020                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6021
6022                         let events = nodes[1].node.get_and_clear_pending_events();
6023                         assert_eq!(events.len(), 1);
6024                         match events[0] {
6025                                 Event::PaymentFailed { payment_hash, .. } => {
6026                                         assert_eq!(payment_hash, payment_hash_2);
6027                                 },
6028                                 _ => panic!("Unexpected event"),
6029                         }
6030
6031                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6032                         assert_eq!(node_txn.len(), 4);
6033
6034                         assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
6035                         check_spends!(node_txn[0], revoked_local_txn[0].clone());
6036
6037                         assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
6038
6039                         let mut witness_lens = BTreeSet::new();
6040                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6041                         witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
6042                         witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
6043                         assert_eq!(witness_lens.len(), 3);
6044                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6045                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
6046                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
6047
6048                         // Next nodes[1] broadcasts its current local tx state:
6049                         assert_eq!(node_txn[1].input.len(), 1);
6050                         assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
6051
6052                         assert_eq!(node_txn[2].input.len(), 1);
6053                         let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
6054                         assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
6055                         assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
6056                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6057                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
6058                 }
6059                 get_announce_close_broadcast_events(&nodes, 0, 1);
6060                 assert_eq!(nodes[0].node.list_channels().len(), 0);
6061                 assert_eq!(nodes[1].node.list_channels().len(), 0);
6062         }
6063
6064         #[test]
6065         fn claim_htlc_outputs_single_tx() {
6066                 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
6067                 let nodes = create_network(2);
6068
6069                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6070
6071                 // Rebalance the network to generate htlc in the two directions
6072                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6073                 // 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
6074                 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
6075                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6076                 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6077
6078                 // Get the will-be-revoked local txn from node[0]
6079                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6080
6081                 //Revoke the old state
6082                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6083
6084                 {
6085                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6086                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6087                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6088
6089                         let events = nodes[1].node.get_and_clear_pending_events();
6090                         assert_eq!(events.len(), 1);
6091                         match events[0] {
6092                                 Event::PaymentFailed { payment_hash, .. } => {
6093                                         assert_eq!(payment_hash, payment_hash_2);
6094                                 },
6095                                 _ => panic!("Unexpected event"),
6096                         }
6097
6098                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6099                         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)
6100
6101                         assert_eq!(node_txn[0], node_txn[7]);
6102                         assert_eq!(node_txn[1], node_txn[8]);
6103                         assert_eq!(node_txn[2], node_txn[9]);
6104                         assert_eq!(node_txn[3], node_txn[10]);
6105                         assert_eq!(node_txn[4], node_txn[11]);
6106                         assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcated by ChannelManger
6107                         assert_eq!(node_txn[4], node_txn[6]);
6108
6109                         assert_eq!(node_txn[0].input.len(), 1);
6110                         assert_eq!(node_txn[1].input.len(), 1);
6111                         assert_eq!(node_txn[2].input.len(), 1);
6112
6113                         let mut revoked_tx_map = HashMap::new();
6114                         revoked_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
6115                         node_txn[0].verify(&revoked_tx_map).unwrap();
6116                         node_txn[1].verify(&revoked_tx_map).unwrap();
6117                         node_txn[2].verify(&revoked_tx_map).unwrap();
6118
6119                         let mut witness_lens = BTreeSet::new();
6120                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6121                         witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
6122                         witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
6123                         assert_eq!(witness_lens.len(), 3);
6124                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6125                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
6126                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
6127
6128                         assert_eq!(node_txn[3].input.len(), 1);
6129                         check_spends!(node_txn[3], chan_1.3.clone());
6130
6131                         assert_eq!(node_txn[4].input.len(), 1);
6132                         let witness_script = node_txn[4].input[0].witness.last().unwrap();
6133                         assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
6134                         assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
6135                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6136                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
6137                 }
6138                 get_announce_close_broadcast_events(&nodes, 0, 1);
6139                 assert_eq!(nodes[0].node.list_channels().len(), 0);
6140                 assert_eq!(nodes[1].node.list_channels().len(), 0);
6141         }
6142
6143         #[test]
6144         fn test_htlc_on_chain_success() {
6145                 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
6146                 // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
6147                 // broadcasting the right event to other nodes in payment path.
6148                 // A --------------------> B ----------------------> C (preimage)
6149                 // First, C should claim the HTLC output via HTLC-Success when its own latest local
6150                 // commitment transaction was broadcast.
6151                 // Then, B should learn the preimage from said transactions, attempting to claim backwards
6152                 // towards B.
6153                 // B should be able to claim via preimage if A then broadcasts its local tx.
6154                 // Finally, when A sees B's latest local commitment transaction it should be able to claim
6155                 // the HTLC output via the preimage it learned (which, once confirmed should generate a
6156                 // PaymentSent event).
6157
6158                 let nodes = create_network(3);
6159
6160                 // Create some initial channels
6161                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6162                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6163
6164                 // Rebalance the network a bit by relaying one payment through all the channels...
6165                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6166                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6167
6168                 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
6169                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6170
6171                 // Broadcast legit commitment tx from C on B's chain
6172                 // Broadcast HTLC Success transation by C on received output from C's commitment tx on B's chain
6173                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6174                 assert_eq!(commitment_tx.len(), 1);
6175                 check_spends!(commitment_tx[0], chan_2.3.clone());
6176                 nodes[2].node.claim_funds(our_payment_preimage);
6177                 check_added_monitors!(nodes[2], 1);
6178                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6179                 assert!(updates.update_add_htlcs.is_empty());
6180                 assert!(updates.update_fail_htlcs.is_empty());
6181                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6182                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
6183
6184                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6185                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6186                 assert_eq!(events.len(), 1);
6187                 match events[0] {
6188                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6189                         _ => panic!("Unexpected event"),
6190                 }
6191                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
6192                 assert_eq!(node_txn.len(), 3);
6193                 assert_eq!(node_txn[1], commitment_tx[0]);
6194                 assert_eq!(node_txn[0], node_txn[2]);
6195                 check_spends!(node_txn[0], commitment_tx[0].clone());
6196                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6197                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6198                 assert_eq!(node_txn[0].lock_time, 0);
6199
6200                 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
6201                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: node_txn}, 1);
6202                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6203                 {
6204                         let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
6205                         assert_eq!(added_monitors.len(), 1);
6206                         assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
6207                         added_monitors.clear();
6208                 }
6209                 assert_eq!(events.len(), 2);
6210                 match events[0] {
6211                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6212                         _ => panic!("Unexpected event"),
6213                 }
6214                 match events[1] {
6215                         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, .. } } => {
6216                                 assert!(update_add_htlcs.is_empty());
6217                                 assert!(update_fail_htlcs.is_empty());
6218                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6219                                 assert!(update_fail_malformed_htlcs.is_empty());
6220                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6221                         },
6222                         _ => panic!("Unexpected event"),
6223                 };
6224                 {
6225                         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
6226                         // commitment transaction with a corresponding HTLC-Timeout transaction, as well as a
6227                         // timeout-claim of the output that nodes[2] just claimed via success.
6228                         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)
6229                         assert_eq!(node_txn.len(), 4);
6230                         assert_eq!(node_txn[0], node_txn[3]);
6231                         check_spends!(node_txn[0], commitment_tx[0].clone());
6232                         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6233                         assert_ne!(node_txn[0].lock_time, 0);
6234                         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
6235                         check_spends!(node_txn[1], chan_2.3.clone());
6236                         check_spends!(node_txn[2], node_txn[1].clone());
6237                         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6238                         assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6239                         assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6240                         assert_ne!(node_txn[2].lock_time, 0);
6241                         node_txn.clear();
6242                 }
6243
6244                 // Broadcast legit commitment tx from A on B's chain
6245                 // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
6246                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6247                 check_spends!(commitment_tx[0], chan_1.3.clone());
6248                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6249                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6250                 assert_eq!(events.len(), 1);
6251                 match events[0] {
6252                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6253                         _ => panic!("Unexpected event"),
6254                 }
6255                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 1 (HTLC-Success) * 2 (block-rescan)
6256                 assert_eq!(node_txn.len(), 3);
6257                 assert_eq!(node_txn[0], node_txn[2]);
6258                 check_spends!(node_txn[0], commitment_tx[0].clone());
6259                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6260                 assert_eq!(node_txn[0].lock_time, 0);
6261                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
6262                 check_spends!(node_txn[1], chan_1.3.clone());
6263                 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6264                 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
6265                 // we already checked the same situation with A.
6266
6267                 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
6268                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
6269                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6270                 assert_eq!(events.len(), 1);
6271                 match events[0] {
6272                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6273                         _ => panic!("Unexpected event"),
6274                 }
6275                 let events = nodes[0].node.get_and_clear_pending_events();
6276                 assert_eq!(events.len(), 1);
6277                 match events[0] {
6278                         Event::PaymentSent { payment_preimage } => {
6279                                 assert_eq!(payment_preimage, our_payment_preimage);
6280                         },
6281                         _ => panic!("Unexpected event"),
6282                 }
6283                 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)
6284                 assert_eq!(node_txn.len(), 4);
6285                 assert_eq!(node_txn[0], node_txn[3]);
6286                 check_spends!(node_txn[0], commitment_tx[0].clone());
6287                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6288                 assert_ne!(node_txn[0].lock_time, 0);
6289                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6290                 check_spends!(node_txn[1], chan_1.3.clone());
6291                 check_spends!(node_txn[2], node_txn[1].clone());
6292                 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6293                 assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6294                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6295                 assert_ne!(node_txn[2].lock_time, 0);
6296         }
6297
6298         #[test]
6299         fn test_htlc_on_chain_timeout() {
6300                 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
6301                 // ChainWatchInterface and timeout the HTLC  bacward accordingly. So here we test that ChannelManager is
6302                 // broadcasting the right event to other nodes in payment path.
6303                 // A ------------------> B ----------------------> C (timeout)
6304                 //    B's commitment tx                 C's commitment tx
6305                 //            \                                  \
6306                 //         B's HTLC timeout tx               B's timeout tx
6307
6308                 let nodes = create_network(3);
6309
6310                 // Create some intial channels
6311                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6312                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6313
6314                 // Rebalance the network a bit by relaying one payment thorugh all the channels...
6315                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6316                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6317
6318                 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
6319                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6320
6321                 // Brodacast legit commitment tx from C on B's chain
6322                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6323                 check_spends!(commitment_tx[0], chan_2.3.clone());
6324                 nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
6325                 {
6326                         let mut added_monitors = nodes[2].chan_monitor.added_monitors.lock().unwrap();
6327                         assert_eq!(added_monitors.len(), 1);
6328                         added_monitors.clear();
6329                 }
6330                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6331                 assert_eq!(events.len(), 1);
6332                 match events[0] {
6333                         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, .. } } => {
6334                                 assert!(update_add_htlcs.is_empty());
6335                                 assert!(!update_fail_htlcs.is_empty());
6336                                 assert!(update_fulfill_htlcs.is_empty());
6337                                 assert!(update_fail_malformed_htlcs.is_empty());
6338                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
6339                         },
6340                         _ => panic!("Unexpected event"),
6341                 };
6342                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6343                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6344                 assert_eq!(events.len(), 1);
6345                 match events[0] {
6346                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6347                         _ => panic!("Unexpected event"),
6348                 }
6349                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
6350                 assert_eq!(node_txn.len(), 1);
6351                 check_spends!(node_txn[0], chan_2.3.clone());
6352                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
6353
6354                 // Broadcast timeout transaction by B on received output fron C's commitment tx on B's chain
6355                 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
6356                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6357                 let timeout_tx;
6358                 {
6359                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6360                         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)
6361                         assert_eq!(node_txn[0], node_txn[5]);
6362                         assert_eq!(node_txn[1], node_txn[6]);
6363                         assert_eq!(node_txn[2], node_txn[7]);
6364                         check_spends!(node_txn[0], commitment_tx[0].clone());
6365                         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6366                         check_spends!(node_txn[1], chan_2.3.clone());
6367                         check_spends!(node_txn[2], node_txn[1].clone());
6368                         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6369                         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6370                         check_spends!(node_txn[3], chan_2.3.clone());
6371                         check_spends!(node_txn[4], node_txn[3].clone());
6372                         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
6373                         assert_eq!(node_txn[4].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6374                         timeout_tx = node_txn[0].clone();
6375                         node_txn.clear();
6376                 }
6377
6378                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![timeout_tx]}, 1);
6379                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6380                 check_added_monitors!(nodes[1], 1);
6381                 assert_eq!(events.len(), 2);
6382                 match events[0] {
6383                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6384                         _ => panic!("Unexpected event"),
6385                 }
6386                 match events[1] {
6387                         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, .. } } => {
6388                                 assert!(update_add_htlcs.is_empty());
6389                                 assert!(!update_fail_htlcs.is_empty());
6390                                 assert!(update_fulfill_htlcs.is_empty());
6391                                 assert!(update_fail_malformed_htlcs.is_empty());
6392                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6393                         },
6394                         _ => panic!("Unexpected event"),
6395                 };
6396                 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
6397                 assert_eq!(node_txn.len(), 0);
6398
6399                 // Broadcast legit commitment tx from B on A's chain
6400                 let commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6401                 check_spends!(commitment_tx[0], chan_1.3.clone());
6402
6403                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6404                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6405                 assert_eq!(events.len(), 1);
6406                 match events[0] {
6407                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6408                         _ => panic!("Unexpected event"),
6409                 }
6410                 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
6411                 assert_eq!(node_txn.len(), 4);
6412                 assert_eq!(node_txn[0], node_txn[3]);
6413                 check_spends!(node_txn[0], commitment_tx[0].clone());
6414                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6415                 check_spends!(node_txn[1], chan_1.3.clone());
6416                 check_spends!(node_txn[2], node_txn[1].clone());
6417                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6418                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6419         }
6420
6421         #[test]
6422         fn test_simple_commitment_revoked_fail_backward() {
6423                 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
6424                 // and fail backward accordingly.
6425
6426                 let nodes = create_network(3);
6427
6428                 // Create some initial channels
6429                 create_announced_chan_between_nodes(&nodes, 0, 1);
6430                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6431
6432                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6433                 // Get the will-be-revoked local txn from nodes[2]
6434                 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6435                 // Revoke the old state
6436                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6437
6438                 route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6439
6440                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6441                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6442                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6443                 check_added_monitors!(nodes[1], 1);
6444                 assert_eq!(events.len(), 2);
6445                 match events[0] {
6446                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6447                         _ => panic!("Unexpected event"),
6448                 }
6449                 match events[1] {
6450                         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, .. } } => {
6451                                 assert!(update_add_htlcs.is_empty());
6452                                 assert_eq!(update_fail_htlcs.len(), 1);
6453                                 assert!(update_fulfill_htlcs.is_empty());
6454                                 assert!(update_fail_malformed_htlcs.is_empty());
6455                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6456
6457                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6458                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6459
6460                                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6461                                 assert_eq!(events.len(), 1);
6462                                 match events[0] {
6463                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6464                                         _ => panic!("Unexpected event"),
6465                                 }
6466                                 let events = nodes[0].node.get_and_clear_pending_events();
6467                                 assert_eq!(events.len(), 1);
6468                                 match events[0] {
6469                                         Event::PaymentFailed { .. } => {},
6470                                         _ => panic!("Unexpected event"),
6471                                 }
6472                         },
6473                         _ => panic!("Unexpected event"),
6474                 }
6475         }
6476
6477         fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool) {
6478                 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
6479                 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
6480                 // commitment transaction anymore.
6481                 // To do this, we have the peer which will broadcast a revoked commitment transaction send
6482                 // a number of update_fail/commitment_signed updates without ever sending the RAA in
6483                 // response to our commitment_signed. This is somewhat misbehavior-y, though not
6484                 // technically disallowed and we should probably handle it reasonably.
6485                 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
6486                 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
6487                 // transactions:
6488                 // * Once we move it out of our holding cell/add it, we will immediately include it in a
6489                 //   commitment_signed (implying it will be in the latest remote commitment transaction).
6490                 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
6491                 //   and once they revoke the previous commitment transaction (allowing us to send a new
6492                 //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
6493                 let mut nodes = create_network(3);
6494
6495                 // Create some initial channels
6496                 create_announced_chan_between_nodes(&nodes, 0, 1);
6497                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6498
6499                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6500                 // Get the will-be-revoked local txn from nodes[2]
6501                 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6502                 // Revoke the old state
6503                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6504
6505                 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6506                 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6507                 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6508
6509                 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, 0));
6510                 check_added_monitors!(nodes[2], 1);
6511                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6512                 assert!(updates.update_add_htlcs.is_empty());
6513                 assert!(updates.update_fulfill_htlcs.is_empty());
6514                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6515                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6516                 assert!(updates.update_fee.is_none());
6517                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6518                 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
6519                 // Drop the last RAA from 3 -> 2
6520
6521                 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, 0));
6522                 check_added_monitors!(nodes[2], 1);
6523                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6524                 assert!(updates.update_add_htlcs.is_empty());
6525                 assert!(updates.update_fulfill_htlcs.is_empty());
6526                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6527                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6528                 assert!(updates.update_fee.is_none());
6529                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6530                 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6531                 check_added_monitors!(nodes[1], 1);
6532                 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
6533                 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6534                 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6535                 check_added_monitors!(nodes[2], 1);
6536
6537                 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, 0));
6538                 check_added_monitors!(nodes[2], 1);
6539                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6540                 assert!(updates.update_add_htlcs.is_empty());
6541                 assert!(updates.update_fulfill_htlcs.is_empty());
6542                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6543                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6544                 assert!(updates.update_fee.is_none());
6545                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6546                 // At this point first_payment_hash has dropped out of the latest two commitment
6547                 // transactions that nodes[1] is tracking...
6548                 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6549                 check_added_monitors!(nodes[1], 1);
6550                 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
6551                 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6552                 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6553                 check_added_monitors!(nodes[2], 1);
6554
6555                 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
6556                 // on nodes[2]'s RAA.
6557                 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
6558                 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6559                 nodes[1].node.send_payment(route, fourth_payment_hash).unwrap();
6560                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
6561                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6562                 check_added_monitors!(nodes[1], 0);
6563
6564                 if deliver_bs_raa {
6565                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa).unwrap();
6566                         // One monitor for the new revocation preimage, one as we generate a commitment for
6567                         // nodes[0] to fail first_payment_hash backwards.
6568                         check_added_monitors!(nodes[1], 2);
6569                 }
6570
6571                 let mut failed_htlcs = HashSet::new();
6572                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6573
6574                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6575                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6576
6577                 let events = nodes[1].node.get_and_clear_pending_events();
6578                 assert_eq!(events.len(), 1);
6579                 match events[0] {
6580                         Event::PaymentFailed { ref payment_hash, .. } => {
6581                                 assert_eq!(*payment_hash, fourth_payment_hash);
6582                         },
6583                         _ => panic!("Unexpected event"),
6584                 }
6585
6586                 if !deliver_bs_raa {
6587                         // If we delivered the RAA already then we already failed first_payment_hash backwards.
6588                         check_added_monitors!(nodes[1], 1);
6589                 }
6590
6591                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6592                 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
6593                 match events[if deliver_bs_raa { 2 } else { 0 }] {
6594                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6595                         _ => panic!("Unexpected event"),
6596                 }
6597                 if deliver_bs_raa {
6598                         match events[0] {
6599                                 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, .. } } => {
6600                                         assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
6601                                         assert_eq!(update_add_htlcs.len(), 1);
6602                                         assert!(update_fulfill_htlcs.is_empty());
6603                                         assert!(update_fail_htlcs.is_empty());
6604                                         assert!(update_fail_malformed_htlcs.is_empty());
6605                                 },
6606                                 _ => panic!("Unexpected event"),
6607                         }
6608                 }
6609                 // Due to the way backwards-failing occurs we do the updates in two steps.
6610                 let updates = match events[1] {
6611                         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, .. } } => {
6612                                 assert!(update_add_htlcs.is_empty());
6613                                 assert_eq!(update_fail_htlcs.len(), 1);
6614                                 assert!(update_fulfill_htlcs.is_empty());
6615                                 assert!(update_fail_malformed_htlcs.is_empty());
6616                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6617
6618                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6619                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
6620                                 check_added_monitors!(nodes[0], 1);
6621                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6622                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6623                                 check_added_monitors!(nodes[1], 1);
6624                                 let bs_second_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6625                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
6626                                 check_added_monitors!(nodes[1], 1);
6627                                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6628                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6629                                 check_added_monitors!(nodes[0], 1);
6630
6631                                 if !deliver_bs_raa {
6632                                         // If we delievered B's RAA we got an unknown preimage error, not something
6633                                         // that we should update our routing table for.
6634                                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6635                                         assert_eq!(events.len(), 1);
6636                                         match events[0] {
6637                                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6638                                                 _ => panic!("Unexpected event"),
6639                                         }
6640                                 }
6641                                 let events = nodes[0].node.get_and_clear_pending_events();
6642                                 assert_eq!(events.len(), 1);
6643                                 match events[0] {
6644                                         Event::PaymentFailed { ref payment_hash, .. } => {
6645                                                 assert!(failed_htlcs.insert(payment_hash.0));
6646                                         },
6647                                         _ => panic!("Unexpected event"),
6648                                 }
6649
6650                                 bs_second_update
6651                         },
6652                         _ => panic!("Unexpected event"),
6653                 };
6654
6655                 assert!(updates.update_add_htlcs.is_empty());
6656                 assert_eq!(updates.update_fail_htlcs.len(), 2);
6657                 assert!(updates.update_fulfill_htlcs.is_empty());
6658                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6659                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6660                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[1]).unwrap();
6661                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6662
6663                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6664                 assert_eq!(events.len(), 2);
6665                 for event in events {
6666                         match event {
6667                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6668                                 _ => panic!("Unexpected event"),
6669                         }
6670                 }
6671
6672                 let events = nodes[0].node.get_and_clear_pending_events();
6673                 assert_eq!(events.len(), 2);
6674                 match events[0] {
6675                         Event::PaymentFailed { ref payment_hash, .. } => {
6676                                 assert!(failed_htlcs.insert(payment_hash.0));
6677                         },
6678                         _ => panic!("Unexpected event"),
6679                 }
6680                 match events[1] {
6681                         Event::PaymentFailed { ref payment_hash, .. } => {
6682                                 assert!(failed_htlcs.insert(payment_hash.0));
6683                         },
6684                         _ => panic!("Unexpected event"),
6685                 }
6686
6687                 assert!(failed_htlcs.contains(&first_payment_hash.0));
6688                 assert!(failed_htlcs.contains(&second_payment_hash.0));
6689                 assert!(failed_htlcs.contains(&third_payment_hash.0));
6690         }
6691
6692         #[test]
6693         fn test_commitment_revoked_fail_backward_exhaustive() {
6694                 do_test_commitment_revoked_fail_backward_exhaustive(false);
6695                 do_test_commitment_revoked_fail_backward_exhaustive(true);
6696         }
6697
6698         #[test]
6699         fn test_htlc_ignore_latest_remote_commitment() {
6700                 // Test that HTLC transactions spending the latest remote commitment transaction are simply
6701                 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
6702                 let nodes = create_network(2);
6703                 create_announced_chan_between_nodes(&nodes, 0, 1);
6704
6705                 route_payment(&nodes[0], &[&nodes[1]], 10000000);
6706                 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
6707                 {
6708                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6709                         assert_eq!(events.len(), 1);
6710                         match events[0] {
6711                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6712                                         assert_eq!(flags & 0b10, 0b10);
6713                                 },
6714                                 _ => panic!("Unexpected event"),
6715                         }
6716                 }
6717
6718                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6719                 assert_eq!(node_txn.len(), 2);
6720
6721                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6722                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6723
6724                 {
6725                         let events = nodes[1].node.get_and_clear_pending_msg_events();
6726                         assert_eq!(events.len(), 1);
6727                         match events[0] {
6728                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6729                                         assert_eq!(flags & 0b10, 0b10);
6730                                 },
6731                                 _ => panic!("Unexpected event"),
6732                         }
6733                 }
6734
6735                 // Duplicate the block_connected call since this may happen due to other listeners
6736                 // registering new transactions
6737                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6738         }
6739
6740         #[test]
6741         fn test_force_close_fail_back() {
6742                 // Check which HTLCs are failed-backwards on channel force-closure
6743                 let mut nodes = create_network(3);
6744                 create_announced_chan_between_nodes(&nodes, 0, 1);
6745                 create_announced_chan_between_nodes(&nodes, 1, 2);
6746
6747                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
6748
6749                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6750
6751                 let mut payment_event = {
6752                         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6753                         check_added_monitors!(nodes[0], 1);
6754
6755                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6756                         assert_eq!(events.len(), 1);
6757                         SendEvent::from_event(events.remove(0))
6758                 };
6759
6760                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6761                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6762
6763                 let events_1 = nodes[1].node.get_and_clear_pending_events();
6764                 assert_eq!(events_1.len(), 1);
6765                 match events_1[0] {
6766                         Event::PendingHTLCsForwardable { .. } => { },
6767                         _ => panic!("Unexpected event"),
6768                 };
6769
6770                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
6771                 nodes[1].node.process_pending_htlc_forwards();
6772
6773                 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6774                 assert_eq!(events_2.len(), 1);
6775                 payment_event = SendEvent::from_event(events_2.remove(0));
6776                 assert_eq!(payment_event.msgs.len(), 1);
6777
6778                 check_added_monitors!(nodes[1], 1);
6779                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6780                 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
6781                 check_added_monitors!(nodes[2], 1);
6782                 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6783
6784                 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
6785                 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
6786                 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
6787
6788                 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
6789                 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6790                 assert_eq!(events_3.len(), 1);
6791                 match events_3[0] {
6792                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6793                                 assert_eq!(flags & 0b10, 0b10);
6794                         },
6795                         _ => panic!("Unexpected event"),
6796                 }
6797
6798                 let tx = {
6799                         let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6800                         // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
6801                         // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
6802                         // back to nodes[1] upon timeout otherwise.
6803                         assert_eq!(node_txn.len(), 1);
6804                         node_txn.remove(0)
6805                 };
6806
6807                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6808                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6809
6810                 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6811                 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
6812                 assert_eq!(events_4.len(), 1);
6813                 match events_4[0] {
6814                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6815                                 assert_eq!(flags & 0b10, 0b10);
6816                         },
6817                         _ => panic!("Unexpected event"),
6818                 }
6819
6820                 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
6821                 {
6822                         let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
6823                         monitors.get_mut(&OutPoint::new(Sha256dHash::from(&payment_event.commitment_msg.channel_id[..]), 0)).unwrap()
6824                                 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
6825                 }
6826                 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6827                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6828                 assert_eq!(node_txn.len(), 1);
6829                 assert_eq!(node_txn[0].input.len(), 1);
6830                 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
6831                 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
6832                 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
6833
6834                 check_spends!(node_txn[0], tx);
6835         }
6836
6837         #[test]
6838         fn test_unconf_chan() {
6839                 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
6840                 let nodes = create_network(2);
6841                 create_announced_chan_between_nodes(&nodes, 0, 1);
6842
6843                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6844                 assert_eq!(channel_state.by_id.len(), 1);
6845                 assert_eq!(channel_state.short_to_id.len(), 1);
6846                 mem::drop(channel_state);
6847
6848                 let mut headers = Vec::new();
6849                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6850                 headers.push(header.clone());
6851                 for _i in 2..100 {
6852                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6853                         headers.push(header.clone());
6854                 }
6855                 while !headers.is_empty() {
6856                         nodes[0].node.block_disconnected(&headers.pop().unwrap());
6857                 }
6858                 {
6859                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6860                         assert_eq!(events.len(), 1);
6861                         match events[0] {
6862                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6863                                         assert_eq!(flags & 0b10, 0b10);
6864                                 },
6865                                 _ => panic!("Unexpected event"),
6866                         }
6867                 }
6868                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6869                 assert_eq!(channel_state.by_id.len(), 0);
6870                 assert_eq!(channel_state.short_to_id.len(), 0);
6871         }
6872
6873         macro_rules! get_chan_reestablish_msgs {
6874                 ($src_node: expr, $dst_node: expr) => {
6875                         {
6876                                 let mut res = Vec::with_capacity(1);
6877                                 for msg in $src_node.node.get_and_clear_pending_msg_events() {
6878                                         if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
6879                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6880                                                 res.push(msg.clone());
6881                                         } else {
6882                                                 panic!("Unexpected event")
6883                                         }
6884                                 }
6885                                 res
6886                         }
6887                 }
6888         }
6889
6890         macro_rules! handle_chan_reestablish_msgs {
6891                 ($src_node: expr, $dst_node: expr) => {
6892                         {
6893                                 let msg_events = $src_node.node.get_and_clear_pending_msg_events();
6894                                 let mut idx = 0;
6895                                 let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
6896                                         idx += 1;
6897                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6898                                         Some(msg.clone())
6899                                 } else {
6900                                         None
6901                                 };
6902
6903                                 let mut revoke_and_ack = None;
6904                                 let mut commitment_update = None;
6905                                 let order = if let Some(ev) = msg_events.get(idx) {
6906                                         idx += 1;
6907                                         match ev {
6908                                                 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6909                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6910                                                         revoke_and_ack = Some(msg.clone());
6911                                                         RAACommitmentOrder::RevokeAndACKFirst
6912                                                 },
6913                                                 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6914                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6915                                                         commitment_update = Some(updates.clone());
6916                                                         RAACommitmentOrder::CommitmentFirst
6917                                                 },
6918                                                 _ => panic!("Unexpected event"),
6919                                         }
6920                                 } else {
6921                                         RAACommitmentOrder::CommitmentFirst
6922                                 };
6923
6924                                 if let Some(ev) = msg_events.get(idx) {
6925                                         match ev {
6926                                                 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6927                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6928                                                         assert!(revoke_and_ack.is_none());
6929                                                         revoke_and_ack = Some(msg.clone());
6930                                                 },
6931                                                 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6932                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6933                                                         assert!(commitment_update.is_none());
6934                                                         commitment_update = Some(updates.clone());
6935                                                 },
6936                                                 _ => panic!("Unexpected event"),
6937                                         }
6938                                 }
6939
6940                                 (funding_locked, revoke_and_ack, commitment_update, order)
6941                         }
6942                 }
6943         }
6944
6945         /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
6946         /// for claims/fails they are separated out.
6947         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)) {
6948                 node_a.node.peer_connected(&node_b.node.get_our_node_id());
6949                 let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
6950                 node_b.node.peer_connected(&node_a.node.get_our_node_id());
6951                 let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
6952
6953                 if send_funding_locked.0 {
6954                         // If a expects a funding_locked, it better not think it has received a revoke_and_ack
6955                         // from b
6956                         for reestablish in reestablish_1.iter() {
6957                                 assert_eq!(reestablish.next_remote_commitment_number, 0);
6958                         }
6959                 }
6960                 if send_funding_locked.1 {
6961                         // If b expects a funding_locked, it better not think it has received a revoke_and_ack
6962                         // from a
6963                         for reestablish in reestablish_2.iter() {
6964                                 assert_eq!(reestablish.next_remote_commitment_number, 0);
6965                         }
6966                 }
6967                 if send_funding_locked.0 || send_funding_locked.1 {
6968                         // If we expect any funding_locked's, both sides better have set
6969                         // next_local_commitment_number to 1
6970                         for reestablish in reestablish_1.iter() {
6971                                 assert_eq!(reestablish.next_local_commitment_number, 1);
6972                         }
6973                         for reestablish in reestablish_2.iter() {
6974                                 assert_eq!(reestablish.next_local_commitment_number, 1);
6975                         }
6976                 }
6977
6978                 let mut resp_1 = Vec::new();
6979                 for msg in reestablish_1 {
6980                         node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg).unwrap();
6981                         resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
6982                 }
6983                 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
6984                         check_added_monitors!(node_b, 1);
6985                 } else {
6986                         check_added_monitors!(node_b, 0);
6987                 }
6988
6989                 let mut resp_2 = Vec::new();
6990                 for msg in reestablish_2 {
6991                         node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg).unwrap();
6992                         resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
6993                 }
6994                 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
6995                         check_added_monitors!(node_a, 1);
6996                 } else {
6997                         check_added_monitors!(node_a, 0);
6998                 }
6999
7000                 // We dont yet support both needing updates, as that would require a different commitment dance:
7001                 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
7002                         (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
7003
7004                 for chan_msgs in resp_1.drain(..) {
7005                         if send_funding_locked.0 {
7006                                 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
7007                                 let announcement_event = node_a.node.get_and_clear_pending_msg_events();
7008                                 if !announcement_event.is_empty() {
7009                                         assert_eq!(announcement_event.len(), 1);
7010                                         if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
7011                                                 //TODO: Test announcement_sigs re-sending
7012                                         } else { panic!("Unexpected event!"); }
7013                                 }
7014                         } else {
7015                                 assert!(chan_msgs.0.is_none());
7016                         }
7017                         if pending_raa.0 {
7018                                 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
7019                                 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
7020                                 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
7021                                 check_added_monitors!(node_a, 1);
7022                         } else {
7023                                 assert!(chan_msgs.1.is_none());
7024                         }
7025                         if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
7026                                 let commitment_update = chan_msgs.2.unwrap();
7027                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
7028                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
7029                                 } else {
7030                                         assert!(commitment_update.update_add_htlcs.is_empty());
7031                                 }
7032                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
7033                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
7034                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
7035                                 for update_add in commitment_update.update_add_htlcs {
7036                                         node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add).unwrap();
7037                                 }
7038                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
7039                                         node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill).unwrap();
7040                                 }
7041                                 for update_fail in commitment_update.update_fail_htlcs {
7042                                         node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail).unwrap();
7043                                 }
7044
7045                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
7046                                         commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
7047                                 } else {
7048                                         node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
7049                                         check_added_monitors!(node_a, 1);
7050                                         let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
7051                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
7052                                         node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7053                                         assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
7054                                         check_added_monitors!(node_b, 1);
7055                                 }
7056                         } else {
7057                                 assert!(chan_msgs.2.is_none());
7058                         }
7059                 }
7060
7061                 for chan_msgs in resp_2.drain(..) {
7062                         if send_funding_locked.1 {
7063                                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
7064                                 let announcement_event = node_b.node.get_and_clear_pending_msg_events();
7065                                 if !announcement_event.is_empty() {
7066                                         assert_eq!(announcement_event.len(), 1);
7067                                         if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
7068                                                 //TODO: Test announcement_sigs re-sending
7069                                         } else { panic!("Unexpected event!"); }
7070                                 }
7071                         } else {
7072                                 assert!(chan_msgs.0.is_none());
7073                         }
7074                         if pending_raa.1 {
7075                                 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
7076                                 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
7077                                 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
7078                                 check_added_monitors!(node_b, 1);
7079                         } else {
7080                                 assert!(chan_msgs.1.is_none());
7081                         }
7082                         if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
7083                                 let commitment_update = chan_msgs.2.unwrap();
7084                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
7085                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
7086                                 }
7087                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
7088                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
7089                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
7090                                 for update_add in commitment_update.update_add_htlcs {
7091                                         node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add).unwrap();
7092                                 }
7093                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
7094                                         node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill).unwrap();
7095                                 }
7096                                 for update_fail in commitment_update.update_fail_htlcs {
7097                                         node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail).unwrap();
7098                                 }
7099
7100                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
7101                                         commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
7102                                 } else {
7103                                         node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
7104                                         check_added_monitors!(node_b, 1);
7105                                         let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
7106                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
7107                                         node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7108                                         assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
7109                                         check_added_monitors!(node_a, 1);
7110                                 }
7111                         } else {
7112                                 assert!(chan_msgs.2.is_none());
7113                         }
7114                 }
7115         }
7116
7117         #[test]
7118         fn test_simple_peer_disconnect() {
7119                 // Test that we can reconnect when there are no lost messages
7120                 let nodes = create_network(3);
7121                 create_announced_chan_between_nodes(&nodes, 0, 1);
7122                 create_announced_chan_between_nodes(&nodes, 1, 2);
7123
7124                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7125                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7126                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7127
7128                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7129                 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7130                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
7131                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
7132
7133                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7134                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7135                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7136
7137                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7138                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7139                 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7140                 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7141
7142                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7143                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7144
7145                 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3);
7146                 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
7147
7148                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
7149                 {
7150                         let events = nodes[0].node.get_and_clear_pending_events();
7151                         assert_eq!(events.len(), 2);
7152                         match events[0] {
7153                                 Event::PaymentSent { payment_preimage } => {
7154                                         assert_eq!(payment_preimage, payment_preimage_3);
7155                                 },
7156                                 _ => panic!("Unexpected event"),
7157                         }
7158                         match events[1] {
7159                                 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
7160                                         assert_eq!(payment_hash, payment_hash_5);
7161                                         assert!(rejected_by_dest);
7162                                 },
7163                                 _ => panic!("Unexpected event"),
7164                         }
7165                 }
7166
7167                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
7168                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
7169         }
7170
7171         fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
7172                 // Test that we can reconnect when in-flight HTLC updates get dropped
7173                 let mut nodes = create_network(2);
7174                 if messages_delivered == 0 {
7175                         create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
7176                         // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
7177                 } else {
7178                         create_announced_chan_between_nodes(&nodes, 0, 1);
7179                 }
7180
7181                 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();
7182                 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7183
7184                 let payment_event = {
7185                         nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
7186                         check_added_monitors!(nodes[0], 1);
7187
7188                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7189                         assert_eq!(events.len(), 1);
7190                         SendEvent::from_event(events.remove(0))
7191                 };
7192                 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
7193
7194                 if messages_delivered < 2 {
7195                         // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
7196                 } else {
7197                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7198                         if messages_delivered >= 3 {
7199                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7200                                 check_added_monitors!(nodes[1], 1);
7201                                 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7202
7203                                 if messages_delivered >= 4 {
7204                                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7205                                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7206                                         check_added_monitors!(nodes[0], 1);
7207
7208                                         if messages_delivered >= 5 {
7209                                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
7210                                                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7211                                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7212                                                 check_added_monitors!(nodes[0], 1);
7213
7214                                                 if messages_delivered >= 6 {
7215                                                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7216                                                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7217                                                         check_added_monitors!(nodes[1], 1);
7218                                                 }
7219                                         }
7220                                 }
7221                         }
7222                 }
7223
7224                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7225                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7226                 if messages_delivered < 3 {
7227                         // Even if the funding_locked messages get exchanged, as long as nothing further was
7228                         // received on either side, both sides will need to resend them.
7229                         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
7230                 } else if messages_delivered == 3 {
7231                         // nodes[0] still wants its RAA + commitment_signed
7232                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
7233                 } else if messages_delivered == 4 {
7234                         // nodes[0] still wants its commitment_signed
7235                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
7236                 } else if messages_delivered == 5 {
7237                         // nodes[1] still wants its final RAA
7238                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
7239                 } else if messages_delivered == 6 {
7240                         // Everything was delivered...
7241                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7242                 }
7243
7244                 let events_1 = nodes[1].node.get_and_clear_pending_events();
7245                 assert_eq!(events_1.len(), 1);
7246                 match events_1[0] {
7247                         Event::PendingHTLCsForwardable { .. } => { },
7248                         _ => panic!("Unexpected event"),
7249                 };
7250
7251                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7252                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7253                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7254
7255                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7256                 nodes[1].node.process_pending_htlc_forwards();
7257
7258                 let events_2 = nodes[1].node.get_and_clear_pending_events();
7259                 assert_eq!(events_2.len(), 1);
7260                 match events_2[0] {
7261                         Event::PaymentReceived { ref payment_hash, amt } => {
7262                                 assert_eq!(payment_hash_1, *payment_hash);
7263                                 assert_eq!(amt, 1000000);
7264                         },
7265                         _ => panic!("Unexpected event"),
7266                 }
7267
7268                 nodes[1].node.claim_funds(payment_preimage_1);
7269                 check_added_monitors!(nodes[1], 1);
7270
7271                 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
7272                 assert_eq!(events_3.len(), 1);
7273                 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
7274                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
7275                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7276                                 assert!(updates.update_add_htlcs.is_empty());
7277                                 assert!(updates.update_fail_htlcs.is_empty());
7278                                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
7279                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
7280                                 assert!(updates.update_fee.is_none());
7281                                 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
7282                         },
7283                         _ => panic!("Unexpected event"),
7284                 };
7285
7286                 if messages_delivered >= 1 {
7287                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc).unwrap();
7288
7289                         let events_4 = nodes[0].node.get_and_clear_pending_events();
7290                         assert_eq!(events_4.len(), 1);
7291                         match events_4[0] {
7292                                 Event::PaymentSent { ref payment_preimage } => {
7293                                         assert_eq!(payment_preimage_1, *payment_preimage);
7294                                 },
7295                                 _ => panic!("Unexpected event"),
7296                         }
7297
7298                         if messages_delivered >= 2 {
7299                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
7300                                 check_added_monitors!(nodes[0], 1);
7301                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7302
7303                                 if messages_delivered >= 3 {
7304                                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7305                                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7306                                         check_added_monitors!(nodes[1], 1);
7307
7308                                         if messages_delivered >= 4 {
7309                                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
7310                                                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7311                                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7312                                                 check_added_monitors!(nodes[1], 1);
7313
7314                                                 if messages_delivered >= 5 {
7315                                                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7316                                                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7317                                                         check_added_monitors!(nodes[0], 1);
7318                                                 }
7319                                         }
7320                                 }
7321                         }
7322                 }
7323
7324                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7325                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7326                 if messages_delivered < 2 {
7327                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
7328                         //TODO: Deduplicate PaymentSent events, then enable this if:
7329                         //if messages_delivered < 1 {
7330                                 let events_4 = nodes[0].node.get_and_clear_pending_events();
7331                                 assert_eq!(events_4.len(), 1);
7332                                 match events_4[0] {
7333                                         Event::PaymentSent { ref payment_preimage } => {
7334                                                 assert_eq!(payment_preimage_1, *payment_preimage);
7335                                         },
7336                                         _ => panic!("Unexpected event"),
7337                                 }
7338                         //}
7339                 } else if messages_delivered == 2 {
7340                         // nodes[0] still wants its RAA + commitment_signed
7341                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
7342                 } else if messages_delivered == 3 {
7343                         // nodes[0] still wants its commitment_signed
7344                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
7345                 } else if messages_delivered == 4 {
7346                         // nodes[1] still wants its final RAA
7347                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
7348                 } else if messages_delivered == 5 {
7349                         // Everything was delivered...
7350                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
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                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7356
7357                 // Channel should still work fine...
7358                 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
7359                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7360         }
7361
7362         #[test]
7363         fn test_drop_messages_peer_disconnect_a() {
7364                 do_test_drop_messages_peer_disconnect(0);
7365                 do_test_drop_messages_peer_disconnect(1);
7366                 do_test_drop_messages_peer_disconnect(2);
7367                 do_test_drop_messages_peer_disconnect(3);
7368         }
7369
7370         #[test]
7371         fn test_drop_messages_peer_disconnect_b() {
7372                 do_test_drop_messages_peer_disconnect(4);
7373                 do_test_drop_messages_peer_disconnect(5);
7374                 do_test_drop_messages_peer_disconnect(6);
7375         }
7376
7377         #[test]
7378         fn test_funding_peer_disconnect() {
7379                 // Test that we can lock in our funding tx while disconnected
7380                 let nodes = create_network(2);
7381                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
7382
7383                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7384                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7385
7386                 confirm_transaction(&nodes[0].chain_monitor, &tx, tx.version);
7387                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7388                 assert_eq!(events_1.len(), 1);
7389                 match events_1[0] {
7390                         MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7391                                 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7392                         },
7393                         _ => panic!("Unexpected event"),
7394                 }
7395
7396                 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7397
7398                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7399                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7400
7401                 confirm_transaction(&nodes[1].chain_monitor, &tx, tx.version);
7402                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7403                 assert_eq!(events_2.len(), 2);
7404                 match events_2[0] {
7405                         MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7406                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7407                         },
7408                         _ => panic!("Unexpected event"),
7409                 }
7410                 match events_2[1] {
7411                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ } => {
7412                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7413                         },
7414                         _ => panic!("Unexpected event"),
7415                 }
7416
7417                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7418
7419                 // TODO: We shouldn't need to manually pass list_usable_chanels here once we support
7420                 // rebroadcasting announcement_signatures upon reconnect.
7421
7422                 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();
7423                 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
7424                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
7425         }
7426
7427         #[test]
7428         fn test_drop_messages_peer_disconnect_dual_htlc() {
7429                 // Test that we can handle reconnecting when both sides of a channel have pending
7430                 // commitment_updates when we disconnect.
7431                 let mut nodes = create_network(2);
7432                 create_announced_chan_between_nodes(&nodes, 0, 1);
7433
7434                 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7435
7436                 // Now try to send a second payment which will fail to send
7437                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7438                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7439
7440                 nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
7441                 check_added_monitors!(nodes[0], 1);
7442
7443                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7444                 assert_eq!(events_1.len(), 1);
7445                 match events_1[0] {
7446                         MessageSendEvent::UpdateHTLCs { .. } => {},
7447                         _ => panic!("Unexpected event"),
7448                 }
7449
7450                 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7451                 check_added_monitors!(nodes[1], 1);
7452
7453                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7454                 assert_eq!(events_2.len(), 1);
7455                 match events_2[0] {
7456                         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 } } => {
7457                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7458                                 assert!(update_add_htlcs.is_empty());
7459                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7460                                 assert!(update_fail_htlcs.is_empty());
7461                                 assert!(update_fail_malformed_htlcs.is_empty());
7462                                 assert!(update_fee.is_none());
7463
7464                                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7465                                 let events_3 = nodes[0].node.get_and_clear_pending_events();
7466                                 assert_eq!(events_3.len(), 1);
7467                                 match events_3[0] {
7468                                         Event::PaymentSent { ref payment_preimage } => {
7469                                                 assert_eq!(*payment_preimage, payment_preimage_1);
7470                                         },
7471                                         _ => panic!("Unexpected event"),
7472                                 }
7473
7474                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
7475                                 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7476                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7477                                 check_added_monitors!(nodes[0], 1);
7478                         },
7479                         _ => panic!("Unexpected event"),
7480                 }
7481
7482                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7483                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7484
7485                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7486                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7487                 assert_eq!(reestablish_1.len(), 1);
7488                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7489                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7490                 assert_eq!(reestablish_2.len(), 1);
7491
7492                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7493                 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7494                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7495                 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7496
7497                 assert!(as_resp.0.is_none());
7498                 assert!(bs_resp.0.is_none());
7499
7500                 assert!(bs_resp.1.is_none());
7501                 assert!(bs_resp.2.is_none());
7502
7503                 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7504
7505                 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
7506                 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
7507                 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7508                 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7509                 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
7510                 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();
7511                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7512                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7513                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7514                 check_added_monitors!(nodes[1], 1);
7515
7516                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap();
7517                 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7518                 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
7519                 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
7520                 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
7521                 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
7522                 assert!(bs_second_commitment_signed.update_fee.is_none());
7523                 check_added_monitors!(nodes[1], 1);
7524
7525                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7526                 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7527                 assert!(as_commitment_signed.update_add_htlcs.is_empty());
7528                 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
7529                 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
7530                 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
7531                 assert!(as_commitment_signed.update_fee.is_none());
7532                 check_added_monitors!(nodes[0], 1);
7533
7534                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
7535                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7536                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7537                 check_added_monitors!(nodes[0], 1);
7538
7539                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
7540                 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7541                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7542                 check_added_monitors!(nodes[1], 1);
7543
7544                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7545                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7546                 check_added_monitors!(nodes[1], 1);
7547
7548                 let events_4 = nodes[1].node.get_and_clear_pending_events();
7549                 assert_eq!(events_4.len(), 1);
7550                 match events_4[0] {
7551                         Event::PendingHTLCsForwardable { .. } => { },
7552                         _ => panic!("Unexpected event"),
7553                 };
7554
7555                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7556                 nodes[1].node.process_pending_htlc_forwards();
7557
7558                 let events_5 = nodes[1].node.get_and_clear_pending_events();
7559                 assert_eq!(events_5.len(), 1);
7560                 match events_5[0] {
7561                         Event::PaymentReceived { ref payment_hash, amt: _ } => {
7562                                 assert_eq!(payment_hash_2, *payment_hash);
7563                         },
7564                         _ => panic!("Unexpected event"),
7565                 }
7566
7567                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
7568                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7569                 check_added_monitors!(nodes[0], 1);
7570
7571                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7572         }
7573
7574         #[test]
7575         fn test_simple_monitor_permanent_update_fail() {
7576                 // Test that we handle a simple permanent monitor update failure
7577                 let mut nodes = create_network(2);
7578                 create_announced_chan_between_nodes(&nodes, 0, 1);
7579
7580                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7581                 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7582
7583                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7584                 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route, payment_hash_1) {} else { panic!(); }
7585                 check_added_monitors!(nodes[0], 1);
7586
7587                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7588                 assert_eq!(events_1.len(), 2);
7589                 match events_1[0] {
7590                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7591                         _ => panic!("Unexpected event"),
7592                 };
7593                 match events_1[1] {
7594                         MessageSendEvent::HandleError { node_id, .. } => assert_eq!(node_id, nodes[1].node.get_our_node_id()),
7595                         _ => panic!("Unexpected event"),
7596                 };
7597
7598                 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7599                 // PaymentFailed event
7600
7601                 assert_eq!(nodes[0].node.list_channels().len(), 0);
7602         }
7603
7604         fn do_test_simple_monitor_temporary_update_fail(disconnect: bool) {
7605                 // Test that we can recover from a simple temporary monitor update failure optionally with
7606                 // a disconnect in between
7607                 let mut nodes = create_network(2);
7608                 create_announced_chan_between_nodes(&nodes, 0, 1);
7609
7610                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7611                 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7612
7613                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7614                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_1) {} else { panic!(); }
7615                 check_added_monitors!(nodes[0], 1);
7616
7617                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7618                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7619                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7620
7621                 if disconnect {
7622                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7623                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7624                         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7625                 }
7626
7627                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7628                 nodes[0].node.test_restore_channel_monitor();
7629                 check_added_monitors!(nodes[0], 1);
7630
7631                 let mut events_2 = nodes[0].node.get_and_clear_pending_msg_events();
7632                 assert_eq!(events_2.len(), 1);
7633                 let payment_event = SendEvent::from_event(events_2.pop().unwrap());
7634                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7635                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7636                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7637
7638                 expect_pending_htlcs_forwardable!(nodes[1]);
7639
7640                 let events_3 = nodes[1].node.get_and_clear_pending_events();
7641                 assert_eq!(events_3.len(), 1);
7642                 match events_3[0] {
7643                         Event::PaymentReceived { ref payment_hash, amt } => {
7644                                 assert_eq!(payment_hash_1, *payment_hash);
7645                                 assert_eq!(amt, 1000000);
7646                         },
7647                         _ => panic!("Unexpected event"),
7648                 }
7649
7650                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_1);
7651
7652                 // Now set it to failed again...
7653                 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7654                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7655                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route, payment_hash_2) {} else { panic!(); }
7656                 check_added_monitors!(nodes[0], 1);
7657
7658                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7659                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7660                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7661
7662                 if disconnect {
7663                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7664                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7665                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7666                 }
7667
7668                 // ...and make sure we can force-close a TemporaryFailure channel with a PermanentFailure
7669                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7670                 nodes[0].node.test_restore_channel_monitor();
7671                 check_added_monitors!(nodes[0], 1);
7672
7673                 let events_5 = nodes[0].node.get_and_clear_pending_msg_events();
7674                 assert_eq!(events_5.len(), 1);
7675                 match events_5[0] {
7676                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7677                         _ => panic!("Unexpected event"),
7678                 }
7679
7680                 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7681                 // PaymentFailed event
7682
7683                 assert_eq!(nodes[0].node.list_channels().len(), 0);
7684         }
7685
7686         #[test]
7687         fn test_simple_monitor_temporary_update_fail() {
7688                 do_test_simple_monitor_temporary_update_fail(false);
7689                 do_test_simple_monitor_temporary_update_fail(true);
7690         }
7691
7692         fn do_test_monitor_temporary_update_fail(disconnect_count: usize) {
7693                 let disconnect_flags = 8 | 16;
7694
7695                 // Test that we can recover from a temporary monitor update failure with some in-flight
7696                 // HTLCs going on at the same time potentially with some disconnection thrown in.
7697                 // * First we route a payment, then get a temporary monitor update failure when trying to
7698                 //   route a second payment. We then claim the first payment.
7699                 // * If disconnect_count is set, we will disconnect at this point (which is likely as
7700                 //   TemporaryFailure likely indicates net disconnect which resulted in failing to update
7701                 //   the ChannelMonitor on a watchtower).
7702                 // * If !(disconnect_count & 16) we deliver a update_fulfill_htlc/CS for the first payment
7703                 //   immediately, otherwise we wait sconnect and deliver them via the reconnect
7704                 //   channel_reestablish processing (ie disconnect_count & 16 makes no sense if
7705                 //   disconnect_count & !disconnect_flags is 0).
7706                 // * We then update the channel monitor, reconnecting if disconnect_count is set and walk
7707                 //   through message sending, potentially disconnect/reconnecting multiple times based on
7708                 //   disconnect_count, to get the update_fulfill_htlc through.
7709                 // * We then walk through more message exchanges to get the original update_add_htlc
7710                 //   through, swapping message ordering based on disconnect_count & 8 and optionally
7711                 //   disconnect/reconnecting based on disconnect_count.
7712                 let mut nodes = create_network(2);
7713                 create_announced_chan_between_nodes(&nodes, 0, 1);
7714
7715                 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7716
7717                 // Now try to send a second payment which will fail to send
7718                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7719                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7720
7721                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7722                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_2) {} else { panic!(); }
7723                 check_added_monitors!(nodes[0], 1);
7724
7725                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7726                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7727                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7728
7729                 // Claim the previous payment, which will result in a update_fulfill_htlc/CS from nodes[1]
7730                 // but nodes[0] won't respond since it is frozen.
7731                 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7732                 check_added_monitors!(nodes[1], 1);
7733                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7734                 assert_eq!(events_2.len(), 1);
7735                 let (bs_initial_fulfill, bs_initial_commitment_signed) = match events_2[0] {
7736                         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 } } => {
7737                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7738                                 assert!(update_add_htlcs.is_empty());
7739                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7740                                 assert!(update_fail_htlcs.is_empty());
7741                                 assert!(update_fail_malformed_htlcs.is_empty());
7742                                 assert!(update_fee.is_none());
7743
7744                                 if (disconnect_count & 16) == 0 {
7745                                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7746                                         let events_3 = nodes[0].node.get_and_clear_pending_events();
7747                                         assert_eq!(events_3.len(), 1);
7748                                         match events_3[0] {
7749                                                 Event::PaymentSent { ref payment_preimage } => {
7750                                                         assert_eq!(*payment_preimage, payment_preimage_1);
7751                                                 },
7752                                                 _ => panic!("Unexpected event"),
7753                                         }
7754
7755                                         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) {
7756                                                 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
7757                                         } else { panic!(); }
7758                                 }
7759
7760                                 (update_fulfill_htlcs[0].clone(), commitment_signed.clone())
7761                         },
7762                         _ => panic!("Unexpected event"),
7763                 };
7764
7765                 if disconnect_count & !disconnect_flags > 0 {
7766                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7767                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7768                 }
7769
7770                 // Now fix monitor updating...
7771                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7772                 nodes[0].node.test_restore_channel_monitor();
7773                 check_added_monitors!(nodes[0], 1);
7774
7775                 macro_rules! disconnect_reconnect_peers { () => { {
7776                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7777                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7778
7779                         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7780                         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7781                         assert_eq!(reestablish_1.len(), 1);
7782                         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7783                         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7784                         assert_eq!(reestablish_2.len(), 1);
7785
7786                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7787                         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7788                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7789                         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7790
7791                         assert!(as_resp.0.is_none());
7792                         assert!(bs_resp.0.is_none());
7793
7794                         (reestablish_1, reestablish_2, as_resp, bs_resp)
7795                 } } }
7796
7797                 let (payment_event, initial_revoke_and_ack) = if disconnect_count & !disconnect_flags > 0 {
7798                         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7799                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7800
7801                         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7802                         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7803                         assert_eq!(reestablish_1.len(), 1);
7804                         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7805                         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7806                         assert_eq!(reestablish_2.len(), 1);
7807
7808                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7809                         check_added_monitors!(nodes[0], 0);
7810                         let mut as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7811                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7812                         check_added_monitors!(nodes[1], 0);
7813                         let mut bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7814
7815                         assert!(as_resp.0.is_none());
7816                         assert!(bs_resp.0.is_none());
7817
7818                         assert!(bs_resp.1.is_none());
7819                         if (disconnect_count & 16) == 0 {
7820                                 assert!(bs_resp.2.is_none());
7821
7822                                 assert!(as_resp.1.is_some());
7823                                 assert!(as_resp.2.is_some());
7824                                 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7825                         } else {
7826                                 assert!(bs_resp.2.as_ref().unwrap().update_add_htlcs.is_empty());
7827                                 assert!(bs_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7828                                 assert!(bs_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7829                                 assert!(bs_resp.2.as_ref().unwrap().update_fee.is_none());
7830                                 assert!(bs_resp.2.as_ref().unwrap().update_fulfill_htlcs == vec![bs_initial_fulfill]);
7831                                 assert!(bs_resp.2.as_ref().unwrap().commitment_signed == bs_initial_commitment_signed);
7832
7833                                 assert!(as_resp.1.is_none());
7834
7835                                 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();
7836                                 let events_3 = nodes[0].node.get_and_clear_pending_events();
7837                                 assert_eq!(events_3.len(), 1);
7838                                 match events_3[0] {
7839                                         Event::PaymentSent { ref payment_preimage } => {
7840                                                 assert_eq!(*payment_preimage, payment_preimage_1);
7841                                         },
7842                                         _ => panic!("Unexpected event"),
7843                                 }
7844
7845                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7846                                 let as_resp_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7847                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7848                                 check_added_monitors!(nodes[0], 1);
7849
7850                                 as_resp.1 = Some(as_resp_raa);
7851                                 bs_resp.2 = None;
7852                         }
7853
7854                         if disconnect_count & !disconnect_flags > 1 {
7855                                 let (second_reestablish_1, second_reestablish_2, second_as_resp, second_bs_resp) = disconnect_reconnect_peers!();
7856
7857                                 if (disconnect_count & 16) == 0 {
7858                                         assert!(reestablish_1 == second_reestablish_1);
7859                                         assert!(reestablish_2 == second_reestablish_2);
7860                                 }
7861                                 assert!(as_resp == second_as_resp);
7862                                 assert!(bs_resp == second_bs_resp);
7863                         }
7864
7865                         (SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), as_resp.2.unwrap()), as_resp.1.unwrap())
7866                 } else {
7867                         let mut events_4 = nodes[0].node.get_and_clear_pending_msg_events();
7868                         assert_eq!(events_4.len(), 2);
7869                         (SendEvent::from_event(events_4.remove(0)), match events_4[0] {
7870                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
7871                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7872                                         msg.clone()
7873                                 },
7874                                 _ => panic!("Unexpected event"),
7875                         })
7876                 };
7877
7878                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7879
7880                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7881                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7882                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7883                 // nodes[1] is awaiting an RAA from nodes[0] still so get_event_msg's assert(len == 1) passes
7884                 check_added_monitors!(nodes[1], 1);
7885
7886                 if disconnect_count & !disconnect_flags > 2 {
7887                         let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7888
7889                         assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7890                         assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7891
7892                         assert!(as_resp.2.is_none());
7893                         assert!(bs_resp.2.is_none());
7894                 }
7895
7896                 let as_commitment_update;
7897                 let bs_second_commitment_update;
7898
7899                 macro_rules! handle_bs_raa { () => {
7900                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7901                         as_commitment_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7902                         assert!(as_commitment_update.update_add_htlcs.is_empty());
7903                         assert!(as_commitment_update.update_fulfill_htlcs.is_empty());
7904                         assert!(as_commitment_update.update_fail_htlcs.is_empty());
7905                         assert!(as_commitment_update.update_fail_malformed_htlcs.is_empty());
7906                         assert!(as_commitment_update.update_fee.is_none());
7907                         check_added_monitors!(nodes[0], 1);
7908                 } }
7909
7910                 macro_rules! handle_initial_raa { () => {
7911                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &initial_revoke_and_ack).unwrap();
7912                         bs_second_commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7913                         assert!(bs_second_commitment_update.update_add_htlcs.is_empty());
7914                         assert!(bs_second_commitment_update.update_fulfill_htlcs.is_empty());
7915                         assert!(bs_second_commitment_update.update_fail_htlcs.is_empty());
7916                         assert!(bs_second_commitment_update.update_fail_malformed_htlcs.is_empty());
7917                         assert!(bs_second_commitment_update.update_fee.is_none());
7918                         check_added_monitors!(nodes[1], 1);
7919                 } }
7920
7921                 if (disconnect_count & 8) == 0 {
7922                         handle_bs_raa!();
7923
7924                         if disconnect_count & !disconnect_flags > 3 {
7925                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7926
7927                                 assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7928                                 assert!(bs_resp.1.is_none());
7929
7930                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7931                                 assert!(bs_resp.2.is_none());
7932
7933                                 assert!(as_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7934                         }
7935
7936                         handle_initial_raa!();
7937
7938                         if disconnect_count & !disconnect_flags > 4 {
7939                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7940
7941                                 assert!(as_resp.1.is_none());
7942                                 assert!(bs_resp.1.is_none());
7943
7944                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7945                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7946                         }
7947                 } else {
7948                         handle_initial_raa!();
7949
7950                         if disconnect_count & !disconnect_flags > 3 {
7951                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7952
7953                                 assert!(as_resp.1.is_none());
7954                                 assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7955
7956                                 assert!(as_resp.2.is_none());
7957                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7958
7959                                 assert!(bs_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7960                         }
7961
7962                         handle_bs_raa!();
7963
7964                         if disconnect_count & !disconnect_flags > 4 {
7965                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7966
7967                                 assert!(as_resp.1.is_none());
7968                                 assert!(bs_resp.1.is_none());
7969
7970                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7971                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7972                         }
7973                 }
7974
7975                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_update.commitment_signed).unwrap();
7976                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7977                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7978                 check_added_monitors!(nodes[0], 1);
7979
7980                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_update.commitment_signed).unwrap();
7981                 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7982                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7983                 check_added_monitors!(nodes[1], 1);
7984
7985                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7986                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7987                 check_added_monitors!(nodes[1], 1);
7988
7989                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
7990                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7991                 check_added_monitors!(nodes[0], 1);
7992
7993                 expect_pending_htlcs_forwardable!(nodes[1]);
7994
7995                 let events_5 = nodes[1].node.get_and_clear_pending_events();
7996                 assert_eq!(events_5.len(), 1);
7997                 match events_5[0] {
7998                         Event::PaymentReceived { ref payment_hash, amt } => {
7999                                 assert_eq!(payment_hash_2, *payment_hash);
8000                                 assert_eq!(amt, 1000000);
8001                         },
8002                         _ => panic!("Unexpected event"),
8003                 }
8004
8005                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
8006         }
8007
8008         #[test]
8009         fn test_monitor_temporary_update_fail_a() {
8010                 do_test_monitor_temporary_update_fail(0);
8011                 do_test_monitor_temporary_update_fail(1);
8012                 do_test_monitor_temporary_update_fail(2);
8013                 do_test_monitor_temporary_update_fail(3);
8014                 do_test_monitor_temporary_update_fail(4);
8015                 do_test_monitor_temporary_update_fail(5);
8016         }
8017
8018         #[test]
8019         fn test_monitor_temporary_update_fail_b() {
8020                 do_test_monitor_temporary_update_fail(2 | 8);
8021                 do_test_monitor_temporary_update_fail(3 | 8);
8022                 do_test_monitor_temporary_update_fail(4 | 8);
8023                 do_test_monitor_temporary_update_fail(5 | 8);
8024         }
8025
8026         #[test]
8027         fn test_monitor_temporary_update_fail_c() {
8028                 do_test_monitor_temporary_update_fail(1 | 16);
8029                 do_test_monitor_temporary_update_fail(2 | 16);
8030                 do_test_monitor_temporary_update_fail(3 | 16);
8031                 do_test_monitor_temporary_update_fail(2 | 8 | 16);
8032                 do_test_monitor_temporary_update_fail(3 | 8 | 16);
8033         }
8034
8035         #[test]
8036         fn test_monitor_update_fail_cs() {
8037                 // Tests handling of a monitor update failure when processing an incoming commitment_signed
8038                 let mut nodes = create_network(2);
8039                 create_announced_chan_between_nodes(&nodes, 0, 1);
8040
8041                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8042                 let (payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
8043                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
8044                 check_added_monitors!(nodes[0], 1);
8045
8046                 let send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8047                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8048
8049                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8050                 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() {
8051                         assert_eq!(err, "Failed to update ChannelMonitor");
8052                 } else { panic!(); }
8053                 check_added_monitors!(nodes[1], 1);
8054                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8055
8056                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8057                 nodes[1].node.test_restore_channel_monitor();
8058                 check_added_monitors!(nodes[1], 1);
8059                 let responses = nodes[1].node.get_and_clear_pending_msg_events();
8060                 assert_eq!(responses.len(), 2);
8061
8062                 match responses[0] {
8063                         MessageSendEvent::SendRevokeAndACK { ref msg, ref node_id } => {
8064                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8065                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &msg).unwrap();
8066                                 check_added_monitors!(nodes[0], 1);
8067                         },
8068                         _ => panic!("Unexpected event"),
8069                 }
8070                 match responses[1] {
8071                         MessageSendEvent::UpdateHTLCs { ref updates, ref node_id } => {
8072                                 assert!(updates.update_add_htlcs.is_empty());
8073                                 assert!(updates.update_fulfill_htlcs.is_empty());
8074                                 assert!(updates.update_fail_htlcs.is_empty());
8075                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8076                                 assert!(updates.update_fee.is_none());
8077                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8078
8079                                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8080                                 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() {
8081                                         assert_eq!(err, "Failed to update ChannelMonitor");
8082                                 } else { panic!(); }
8083                                 check_added_monitors!(nodes[0], 1);
8084                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8085                         },
8086                         _ => panic!("Unexpected event"),
8087                 }
8088
8089                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
8090                 nodes[0].node.test_restore_channel_monitor();
8091                 check_added_monitors!(nodes[0], 1);
8092
8093                 let final_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8094                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &final_raa).unwrap();
8095                 check_added_monitors!(nodes[1], 1);
8096
8097                 let mut events = nodes[1].node.get_and_clear_pending_events();
8098                 assert_eq!(events.len(), 1);
8099                 match events[0] {
8100                         Event::PendingHTLCsForwardable { .. } => { },
8101                         _ => panic!("Unexpected event"),
8102                 };
8103                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8104                 nodes[1].node.process_pending_htlc_forwards();
8105
8106                 events = nodes[1].node.get_and_clear_pending_events();
8107                 assert_eq!(events.len(), 1);
8108                 match events[0] {
8109                         Event::PaymentReceived { payment_hash, amt } => {
8110                                 assert_eq!(payment_hash, our_payment_hash);
8111                                 assert_eq!(amt, 1000000);
8112                         },
8113                         _ => panic!("Unexpected event"),
8114                 };
8115
8116                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
8117         }
8118
8119         fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) {
8120                 // Tests handling of a monitor update failure when processing an incoming RAA
8121                 let mut nodes = create_network(3);
8122                 create_announced_chan_between_nodes(&nodes, 0, 1);
8123                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
8124
8125                 // Rebalance a bit so that we can send backwards from 2 to 1.
8126                 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 5000000);
8127
8128                 // Route a first payment that we'll fail backwards
8129                 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
8130
8131                 // Fail the payment backwards, failing the monitor update on nodes[1]'s receipt of the RAA
8132                 assert!(nodes[2].node.fail_htlc_backwards(&payment_hash_1, 0));
8133                 check_added_monitors!(nodes[2], 1);
8134
8135                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8136                 assert!(updates.update_add_htlcs.is_empty());
8137                 assert!(updates.update_fulfill_htlcs.is_empty());
8138                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8139                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8140                 assert!(updates.update_fee.is_none());
8141                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
8142
8143                 let bs_revoke_and_ack = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
8144                 check_added_monitors!(nodes[0], 0);
8145
8146                 // While the second channel is AwaitingRAA, forward a second payment to get it into the
8147                 // holding cell.
8148                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
8149                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8150                 nodes[0].node.send_payment(route, payment_hash_2).unwrap();
8151                 check_added_monitors!(nodes[0], 1);
8152
8153                 let mut send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8154                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8155                 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false);
8156
8157                 let events_1 = nodes[1].node.get_and_clear_pending_events();
8158                 assert_eq!(events_1.len(), 1);
8159                 match events_1[0] {
8160                         Event::PendingHTLCsForwardable { .. } => { },
8161                         _ => panic!("Unexpected event"),
8162                 };
8163
8164                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8165                 nodes[1].node.process_pending_htlc_forwards();
8166                 check_added_monitors!(nodes[1], 0);
8167                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8168
8169                 // Now fail monitor updating.
8170                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8171                 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() {
8172                         assert_eq!(err, "Failed to update ChannelMonitor");
8173                 } else { panic!(); }
8174                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8175                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8176                 check_added_monitors!(nodes[1], 1);
8177
8178                 // Attempt to forward a third payment but fail due to the second channel being unavailable
8179                 // for forwarding.
8180
8181                 let (_, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
8182                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8183                 nodes[0].node.send_payment(route, payment_hash_3).unwrap();
8184                 check_added_monitors!(nodes[0], 1);
8185
8186                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(()); // We succeed in updating the monitor for the first channel
8187                 send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8188                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8189                 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
8190                 check_added_monitors!(nodes[1], 0);
8191
8192                 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8193                 assert_eq!(events_2.len(), 1);
8194                 match events_2.remove(0) {
8195                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
8196                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8197                                 assert!(updates.update_fulfill_htlcs.is_empty());
8198                                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8199                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8200                                 assert!(updates.update_add_htlcs.is_empty());
8201                                 assert!(updates.update_fee.is_none());
8202
8203                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
8204                                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
8205
8206                                 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
8207                                 assert_eq!(msg_events.len(), 1);
8208                                 match msg_events[0] {
8209                                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
8210                                                 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
8211                                                 assert_eq!(msg.contents.flags & 2, 2); // temp disabled
8212                                         },
8213                                         _ => panic!("Unexpected event"),
8214                                 }
8215
8216                                 let events = nodes[0].node.get_and_clear_pending_events();
8217                                 assert_eq!(events.len(), 1);
8218                                 if let Event::PaymentFailed { payment_hash, rejected_by_dest, .. } = events[0] {
8219                                         assert_eq!(payment_hash, payment_hash_3);
8220                                         assert!(!rejected_by_dest);
8221                                 } else { panic!("Unexpected event!"); }
8222                         },
8223                         _ => panic!("Unexpected event type!"),
8224                 };
8225
8226                 let (payment_preimage_4, payment_hash_4) = if test_ignore_second_cs {
8227                         // Try to route another payment backwards from 2 to make sure 1 holds off on responding
8228                         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[0]);
8229                         let route = nodes[2].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8230                         nodes[2].node.send_payment(route, payment_hash_4).unwrap();
8231                         check_added_monitors!(nodes[2], 1);
8232
8233                         send_event = SendEvent::from_event(nodes[2].node.get_and_clear_pending_msg_events().remove(0));
8234                         nodes[1].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8235                         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) {
8236                                 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
8237                         } else { panic!(); }
8238                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8239                         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8240                         (Some(payment_preimage_4), Some(payment_hash_4))
8241                 } else { (None, None) };
8242
8243                 // Restore monitor updating, ensuring we immediately get a fail-back update and a
8244                 // update_add update.
8245                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8246                 nodes[1].node.test_restore_channel_monitor();
8247                 check_added_monitors!(nodes[1], 2);
8248
8249                 let mut events_3 = nodes[1].node.get_and_clear_pending_msg_events();
8250                 if test_ignore_second_cs {
8251                         assert_eq!(events_3.len(), 3);
8252                 } else {
8253                         assert_eq!(events_3.len(), 2);
8254                 }
8255
8256                 // Note that the ordering of the events for different nodes is non-prescriptive, though the
8257                 // ordering of the two events that both go to nodes[2] have to stay in the same order.
8258                 let messages_a = match events_3.pop().unwrap() {
8259                         MessageSendEvent::UpdateHTLCs { node_id, mut updates } => {
8260                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8261                                 assert!(updates.update_fulfill_htlcs.is_empty());
8262                                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8263                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8264                                 assert!(updates.update_add_htlcs.is_empty());
8265                                 assert!(updates.update_fee.is_none());
8266                                 (updates.update_fail_htlcs.remove(0), updates.commitment_signed)
8267                         },
8268                         _ => panic!("Unexpected event type!"),
8269                 };
8270                 let raa = if test_ignore_second_cs {
8271                         match events_3.remove(1) {
8272                                 MessageSendEvent::SendRevokeAndACK { node_id, msg } => {
8273                                         assert_eq!(node_id, nodes[2].node.get_our_node_id());
8274                                         Some(msg.clone())
8275                                 },
8276                                 _ => panic!("Unexpected event"),
8277                         }
8278                 } else { None };
8279                 let send_event_b = SendEvent::from_event(events_3.remove(0));
8280                 assert_eq!(send_event_b.node_id, nodes[2].node.get_our_node_id());
8281
8282                 // Now deliver the new messages...
8283
8284                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &messages_a.0).unwrap();
8285                 commitment_signed_dance!(nodes[0], nodes[1], messages_a.1, false);
8286                 let events_4 = nodes[0].node.get_and_clear_pending_events();
8287                 assert_eq!(events_4.len(), 1);
8288                 if let Event::PaymentFailed { payment_hash, rejected_by_dest, .. } = events_4[0] {
8289                         assert_eq!(payment_hash, payment_hash_1);
8290                         assert!(rejected_by_dest);
8291                 } else { panic!("Unexpected event!"); }
8292
8293                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event_b.msgs[0]).unwrap();
8294                 if test_ignore_second_cs {
8295                         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event_b.commitment_msg).unwrap();
8296                         check_added_monitors!(nodes[2], 1);
8297                         let bs_revoke_and_ack = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8298                         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa.unwrap()).unwrap();
8299                         check_added_monitors!(nodes[2], 1);
8300                         let bs_cs = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8301                         assert!(bs_cs.update_add_htlcs.is_empty());
8302                         assert!(bs_cs.update_fail_htlcs.is_empty());
8303                         assert!(bs_cs.update_fail_malformed_htlcs.is_empty());
8304                         assert!(bs_cs.update_fulfill_htlcs.is_empty());
8305                         assert!(bs_cs.update_fee.is_none());
8306
8307                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
8308                         check_added_monitors!(nodes[1], 1);
8309                         let as_cs = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
8310                         assert!(as_cs.update_add_htlcs.is_empty());
8311                         assert!(as_cs.update_fail_htlcs.is_empty());
8312                         assert!(as_cs.update_fail_malformed_htlcs.is_empty());
8313                         assert!(as_cs.update_fulfill_htlcs.is_empty());
8314                         assert!(as_cs.update_fee.is_none());
8315
8316                         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_cs.commitment_signed).unwrap();
8317                         check_added_monitors!(nodes[1], 1);
8318                         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
8319
8320                         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_cs.commitment_signed).unwrap();
8321                         check_added_monitors!(nodes[2], 1);
8322                         let bs_second_raa = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8323
8324                         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
8325                         check_added_monitors!(nodes[2], 1);
8326                         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
8327
8328                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_second_raa).unwrap();
8329                         check_added_monitors!(nodes[1], 1);
8330                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8331                 } else {
8332                         commitment_signed_dance!(nodes[2], nodes[1], send_event_b.commitment_msg, false);
8333                 }
8334
8335                 let events_5 = nodes[2].node.get_and_clear_pending_events();
8336                 assert_eq!(events_5.len(), 1);
8337                 match events_5[0] {
8338                         Event::PendingHTLCsForwardable { .. } => { },
8339                         _ => panic!("Unexpected event"),
8340                 };
8341
8342                 nodes[2].node.channel_state.lock().unwrap().next_forward = Instant::now();
8343                 nodes[2].node.process_pending_htlc_forwards();
8344
8345                 let events_6 = nodes[2].node.get_and_clear_pending_events();
8346                 assert_eq!(events_6.len(), 1);
8347                 match events_6[0] {
8348                         Event::PaymentReceived { payment_hash, .. } => { assert_eq!(payment_hash, payment_hash_2); },
8349                         _ => panic!("Unexpected event"),
8350                 };
8351
8352                 if test_ignore_second_cs {
8353                         let events_7 = nodes[1].node.get_and_clear_pending_events();
8354                         assert_eq!(events_7.len(), 1);
8355                         match events_7[0] {
8356                                 Event::PendingHTLCsForwardable { .. } => { },
8357                                 _ => panic!("Unexpected event"),
8358                         };
8359
8360                         nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8361                         nodes[1].node.process_pending_htlc_forwards();
8362                         check_added_monitors!(nodes[1], 1);
8363
8364                         send_event = SendEvent::from_node(&nodes[1]);
8365                         assert_eq!(send_event.node_id, nodes[0].node.get_our_node_id());
8366                         assert_eq!(send_event.msgs.len(), 1);
8367                         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8368                         commitment_signed_dance!(nodes[0], nodes[1], send_event.commitment_msg, false);
8369
8370                         let events_8 = nodes[0].node.get_and_clear_pending_events();
8371                         assert_eq!(events_8.len(), 1);
8372                         match events_8[0] {
8373                                 Event::PendingHTLCsForwardable { .. } => { },
8374                                 _ => panic!("Unexpected event"),
8375                         };
8376
8377                         nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
8378                         nodes[0].node.process_pending_htlc_forwards();
8379
8380                         let events_9 = nodes[0].node.get_and_clear_pending_events();
8381                         assert_eq!(events_9.len(), 1);
8382                         match events_9[0] {
8383                                 Event::PaymentReceived { payment_hash, .. } => assert_eq!(payment_hash, payment_hash_4.unwrap()),
8384                                 _ => panic!("Unexpected event"),
8385                         };
8386                         claim_payment(&nodes[2], &[&nodes[1], &nodes[0]], payment_preimage_4.unwrap());
8387                 }
8388
8389                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
8390         }
8391
8392         #[test]
8393         fn test_monitor_update_fail_raa() {
8394                 do_test_monitor_update_fail_raa(false);
8395                 do_test_monitor_update_fail_raa(true);
8396         }
8397
8398         #[test]
8399         fn test_monitor_update_fail_reestablish() {
8400                 // Simple test for message retransmission after monitor update failure on
8401                 // channel_reestablish generating a monitor update (which comes from freeing holding cell
8402                 // HTLCs).
8403                 let mut nodes = create_network(3);
8404                 create_announced_chan_between_nodes(&nodes, 0, 1);
8405                 create_announced_chan_between_nodes(&nodes, 1, 2);
8406
8407                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
8408
8409                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8410                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8411
8412                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
8413                 check_added_monitors!(nodes[2], 1);
8414                 let mut updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8415                 assert!(updates.update_add_htlcs.is_empty());
8416                 assert!(updates.update_fail_htlcs.is_empty());
8417                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8418                 assert!(updates.update_fee.is_none());
8419                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8420                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8421                 check_added_monitors!(nodes[1], 1);
8422                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8423                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
8424
8425                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8426                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8427                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8428
8429                 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
8430                 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8431
8432                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
8433
8434                 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() {
8435                         assert_eq!(err, "Failed to update ChannelMonitor");
8436                 } else { panic!(); }
8437                 check_added_monitors!(nodes[1], 1);
8438
8439                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8440                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8441
8442                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8443                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8444
8445                 assert!(as_reestablish == get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()));
8446                 assert!(bs_reestablish == get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id()));
8447
8448                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
8449
8450                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish).unwrap();
8451                 check_added_monitors!(nodes[1], 0);
8452                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8453
8454                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8455                 nodes[1].node.test_restore_channel_monitor();
8456                 check_added_monitors!(nodes[1], 1);
8457
8458                 updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8459                 assert!(updates.update_add_htlcs.is_empty());
8460                 assert!(updates.update_fail_htlcs.is_empty());
8461                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8462                 assert!(updates.update_fee.is_none());
8463                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8464                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8465                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
8466
8467                 let events = nodes[0].node.get_and_clear_pending_events();
8468                 assert_eq!(events.len(), 1);
8469                 match events[0] {
8470                         Event::PaymentSent { payment_preimage, .. } => assert_eq!(payment_preimage, our_payment_preimage),
8471                         _ => panic!("Unexpected event"),
8472                 }
8473         }
8474
8475         #[test]
8476         fn test_invalid_channel_announcement() {
8477                 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
8478                 let secp_ctx = Secp256k1::new();
8479                 let nodes = create_network(2);
8480
8481                 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1]);
8482
8483                 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8484                 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
8485                 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
8486                 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
8487
8488                 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 } );
8489
8490                 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
8491                 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
8492
8493                 let as_network_key = nodes[0].node.get_our_node_id();
8494                 let bs_network_key = nodes[1].node.get_our_node_id();
8495
8496                 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
8497
8498                 let mut chan_announcement;
8499
8500                 macro_rules! dummy_unsigned_msg {
8501                         () => {
8502                                 msgs::UnsignedChannelAnnouncement {
8503                                         features: msgs::GlobalFeatures::new(),
8504                                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
8505                                         short_channel_id: as_chan.get_short_channel_id().unwrap(),
8506                                         node_id_1: if were_node_one { as_network_key } else { bs_network_key },
8507                                         node_id_2: if were_node_one { bs_network_key } else { as_network_key },
8508                                         bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
8509                                         bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
8510                                         excess_data: Vec::new(),
8511                                 };
8512                         }
8513                 }
8514
8515                 macro_rules! sign_msg {
8516                         ($unsigned_msg: expr) => {
8517                                 let msghash = Message::from_slice(&Sha256dHash::from_data(&$unsigned_msg.encode()[..])[..]).unwrap();
8518                                 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
8519                                 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
8520                                 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].node.our_network_key);
8521                                 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].node.our_network_key);
8522                                 chan_announcement = msgs::ChannelAnnouncement {
8523                                         node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
8524                                         node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
8525                                         bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
8526                                         bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
8527                                         contents: $unsigned_msg
8528                                 }
8529                         }
8530                 }
8531
8532                 let unsigned_msg = dummy_unsigned_msg!();
8533                 sign_msg!(unsigned_msg);
8534                 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
8535                 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 } );
8536
8537                 // Configured with Network::Testnet
8538                 let mut unsigned_msg = dummy_unsigned_msg!();
8539                 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
8540                 sign_msg!(unsigned_msg);
8541                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
8542
8543                 let mut unsigned_msg = dummy_unsigned_msg!();
8544                 unsigned_msg.chain_hash = Sha256dHash::from_data(&[1,2,3,4,5,6,7,8,9]);
8545                 sign_msg!(unsigned_msg);
8546                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
8547         }
8548
8549         struct VecWriter(Vec<u8>);
8550         impl Writer for VecWriter {
8551                 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
8552                         self.0.extend_from_slice(buf);
8553                         Ok(())
8554                 }
8555                 fn size_hint(&mut self, size: usize) {
8556                         self.0.reserve_exact(size);
8557                 }
8558         }
8559
8560         #[test]
8561         fn test_no_txn_manager_serialize_deserialize() {
8562                 let mut nodes = create_network(2);
8563
8564                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
8565
8566                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8567
8568                 let nodes_0_serialized = nodes[0].node.encode();
8569                 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8570                 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8571
8572                 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())));
8573                 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8574                 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8575                 assert!(chan_0_monitor_read.is_empty());
8576
8577                 let mut nodes_0_read = &nodes_0_serialized[..];
8578                 let config = UserConfig::new();
8579                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8580                 let (_, nodes_0_deserialized) = {
8581                         let mut channel_monitors = HashMap::new();
8582                         channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8583                         <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8584                                 default_config: config,
8585                                 keys_manager,
8586                                 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8587                                 monitor: nodes[0].chan_monitor.clone(),
8588                                 chain_monitor: nodes[0].chain_monitor.clone(),
8589                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8590                                 logger: Arc::new(test_utils::TestLogger::new()),
8591                                 channel_monitors: &channel_monitors,
8592                         }).unwrap()
8593                 };
8594                 assert!(nodes_0_read.is_empty());
8595
8596                 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8597                 nodes[0].node = Arc::new(nodes_0_deserialized);
8598                 let nodes_0_as_listener: Arc<ChainListener> = nodes[0].node.clone();
8599                 nodes[0].chain_monitor.register_listener(Arc::downgrade(&nodes_0_as_listener));
8600                 assert_eq!(nodes[0].node.list_channels().len(), 1);
8601                 check_added_monitors!(nodes[0], 1);
8602
8603                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8604                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
8605                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8606                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
8607
8608                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
8609                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8610                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
8611                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8612
8613                 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8614                 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8615                 for node in nodes.iter() {
8616                         assert!(node.router.handle_channel_announcement(&announcement).unwrap());
8617                         node.router.handle_channel_update(&as_update).unwrap();
8618                         node.router.handle_channel_update(&bs_update).unwrap();
8619                 }
8620
8621                 send_payment(&nodes[0], &[&nodes[1]], 1000000);
8622         }
8623
8624         #[test]
8625         fn test_simple_manager_serialize_deserialize() {
8626                 let mut nodes = create_network(2);
8627                 create_announced_chan_between_nodes(&nodes, 0, 1);
8628
8629                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8630                 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8631
8632                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8633
8634                 let nodes_0_serialized = nodes[0].node.encode();
8635                 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8636                 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8637
8638                 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())));
8639                 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8640                 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8641                 assert!(chan_0_monitor_read.is_empty());
8642
8643                 let mut nodes_0_read = &nodes_0_serialized[..];
8644                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8645                 let (_, nodes_0_deserialized) = {
8646                         let mut channel_monitors = HashMap::new();
8647                         channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8648                         <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8649                                 default_config: UserConfig::new(),
8650                                 keys_manager,
8651                                 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8652                                 monitor: nodes[0].chan_monitor.clone(),
8653                                 chain_monitor: nodes[0].chain_monitor.clone(),
8654                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8655                                 logger: Arc::new(test_utils::TestLogger::new()),
8656                                 channel_monitors: &channel_monitors,
8657                         }).unwrap()
8658                 };
8659                 assert!(nodes_0_read.is_empty());
8660
8661                 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8662                 nodes[0].node = Arc::new(nodes_0_deserialized);
8663                 check_added_monitors!(nodes[0], 1);
8664
8665                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8666
8667                 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
8668                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
8669         }
8670
8671         #[test]
8672         fn test_manager_serialize_deserialize_inconsistent_monitor() {
8673                 // Test deserializing a ChannelManager with a out-of-date ChannelMonitor
8674                 let mut nodes = create_network(4);
8675                 create_announced_chan_between_nodes(&nodes, 0, 1);
8676                 create_announced_chan_between_nodes(&nodes, 2, 0);
8677                 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3);
8678
8679                 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
8680
8681                 // Serialize the ChannelManager here, but the monitor we keep up-to-date
8682                 let nodes_0_serialized = nodes[0].node.encode();
8683
8684                 route_payment(&nodes[0], &[&nodes[3]], 1000000);
8685                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8686                 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8687                 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8688
8689                 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
8690                 // nodes[3])
8691                 let mut node_0_monitors_serialized = Vec::new();
8692                 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
8693                         let mut writer = VecWriter(Vec::new());
8694                         monitor.1.write_for_disk(&mut writer).unwrap();
8695                         node_0_monitors_serialized.push(writer.0);
8696                 }
8697
8698                 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())));
8699                 let mut node_0_monitors = Vec::new();
8700                 for serialized in node_0_monitors_serialized.iter() {
8701                         let mut read = &serialized[..];
8702                         let (_, monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
8703                         assert!(read.is_empty());
8704                         node_0_monitors.push(monitor);
8705                 }
8706
8707                 let mut nodes_0_read = &nodes_0_serialized[..];
8708                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8709                 let (_, nodes_0_deserialized) = <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8710                         default_config: UserConfig::new(),
8711                         keys_manager,
8712                         fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8713                         monitor: nodes[0].chan_monitor.clone(),
8714                         chain_monitor: nodes[0].chain_monitor.clone(),
8715                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8716                         logger: Arc::new(test_utils::TestLogger::new()),
8717                         channel_monitors: &node_0_monitors.iter().map(|monitor| { (monitor.get_funding_txo().unwrap(), monitor) }).collect(),
8718                 }).unwrap();
8719                 assert!(nodes_0_read.is_empty());
8720
8721                 { // Channel close should result in a commitment tx and an HTLC tx
8722                         let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8723                         assert_eq!(txn.len(), 2);
8724                         assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
8725                         assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
8726                 }
8727
8728                 for monitor in node_0_monitors.drain(..) {
8729                         assert!(nodes[0].chan_monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor).is_ok());
8730                         check_added_monitors!(nodes[0], 1);
8731                 }
8732                 nodes[0].node = Arc::new(nodes_0_deserialized);
8733
8734                 // nodes[1] and nodes[2] have no lost state with nodes[0]...
8735                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8736                 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8737                 //... and we can even still claim the payment!
8738                 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
8739
8740                 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id());
8741                 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8742                 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id());
8743                 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) {
8744                         assert_eq!(msg.channel_id, channel_id);
8745                 } else { panic!("Unexpected result"); }
8746         }
8747
8748         macro_rules! check_spendable_outputs {
8749                 ($node: expr, $der_idx: expr) => {
8750                         {
8751                                 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
8752                                 let mut txn = Vec::new();
8753                                 for event in events {
8754                                         match event {
8755                                                 Event::SpendableOutputs { ref outputs } => {
8756                                                         for outp in outputs {
8757                                                                 match *outp {
8758                                                                         SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
8759                                                                                 let input = TxIn {
8760                                                                                         previous_output: outpoint.clone(),
8761                                                                                         script_sig: Script::new(),
8762                                                                                         sequence: 0,
8763                                                                                         witness: Vec::new(),
8764                                                                                 };
8765                                                                                 let outp = TxOut {
8766                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8767                                                                                         value: output.value,
8768                                                                                 };
8769                                                                                 let mut spend_tx = Transaction {
8770                                                                                         version: 2,
8771                                                                                         lock_time: 0,
8772                                                                                         input: vec![input],
8773                                                                                         output: vec![outp],
8774                                                                                 };
8775                                                                                 let secp_ctx = Secp256k1::new();
8776                                                                                 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
8777                                                                                 let witness_script = Address::p2pkh(&remotepubkey, Network::Testnet).script_pubkey();
8778                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8779                                                                                 let remotesig = secp_ctx.sign(&sighash, key);
8780                                                                                 spend_tx.input[0].witness.push(remotesig.serialize_der(&secp_ctx).to_vec());
8781                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8782                                                                                 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
8783                                                                                 txn.push(spend_tx);
8784                                                                         },
8785                                                                         SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
8786                                                                                 let input = TxIn {
8787                                                                                         previous_output: outpoint.clone(),
8788                                                                                         script_sig: Script::new(),
8789                                                                                         sequence: *to_self_delay as u32,
8790                                                                                         witness: Vec::new(),
8791                                                                                 };
8792                                                                                 let outp = TxOut {
8793                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8794                                                                                         value: output.value,
8795                                                                                 };
8796                                                                                 let mut spend_tx = Transaction {
8797                                                                                         version: 2,
8798                                                                                         lock_time: 0,
8799                                                                                         input: vec![input],
8800                                                                                         output: vec![outp],
8801                                                                                 };
8802                                                                                 let secp_ctx = Secp256k1::new();
8803                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
8804                                                                                 let local_delaysig = secp_ctx.sign(&sighash, key);
8805                                                                                 spend_tx.input[0].witness.push(local_delaysig.serialize_der(&secp_ctx).to_vec());
8806                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8807                                                                                 spend_tx.input[0].witness.push(vec!(0));
8808                                                                                 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
8809                                                                                 txn.push(spend_tx);
8810                                                                         },
8811                                                                         SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
8812                                                                                 let secp_ctx = Secp256k1::new();
8813                                                                                 let input = TxIn {
8814                                                                                         previous_output: outpoint.clone(),
8815                                                                                         script_sig: Script::new(),
8816                                                                                         sequence: 0,
8817                                                                                         witness: Vec::new(),
8818                                                                                 };
8819                                                                                 let outp = TxOut {
8820                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8821                                                                                         value: output.value,
8822                                                                                 };
8823                                                                                 let mut spend_tx = Transaction {
8824                                                                                         version: 2,
8825                                                                                         lock_time: 0,
8826                                                                                         input: vec![input],
8827                                                                                         output: vec![outp.clone()],
8828                                                                                 };
8829                                                                                 let secret = {
8830                                                                                         match ExtendedPrivKey::new_master(&secp_ctx, Network::Testnet, &$node.node_seed) {
8831                                                                                                 Ok(master_key) => {
8832                                                                                                         match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx)) {
8833                                                                                                                 Ok(key) => key,
8834                                                                                                                 Err(_) => panic!("Your RNG is busted"),
8835                                                                                                         }
8836                                                                                                 }
8837                                                                                                 Err(_) => panic!("Your rng is busted"),
8838                                                                                         }
8839                                                                                 };
8840                                                                                 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
8841                                                                                 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
8842                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8843                                                                                 let sig = secp_ctx.sign(&sighash, &secret.secret_key);
8844                                                                                 spend_tx.input[0].witness.push(sig.serialize_der(&secp_ctx).to_vec());
8845                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8846                                                                                 spend_tx.input[0].witness.push(pubkey.serialize().to_vec());
8847                                                                                 txn.push(spend_tx);
8848                                                                         },
8849                                                                 }
8850                                                         }
8851                                                 },
8852                                                 _ => panic!("Unexpected event"),
8853                                         };
8854                                 }
8855                                 txn
8856                         }
8857                 }
8858         }
8859
8860         #[test]
8861         fn test_claim_sizeable_push_msat() {
8862                 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
8863                 let nodes = create_network(2);
8864
8865                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8866                 nodes[1].node.force_close_channel(&chan.2);
8867                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8868                 match events[0] {
8869                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8870                         _ => panic!("Unexpected event"),
8871                 }
8872                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8873                 assert_eq!(node_txn.len(), 1);
8874                 check_spends!(node_txn[0], chan.3.clone());
8875                 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
8876
8877                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8878                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8879                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8880                 assert_eq!(spend_txn.len(), 1);
8881                 check_spends!(spend_txn[0], node_txn[0].clone());
8882         }
8883
8884         #[test]
8885         fn test_claim_on_remote_sizeable_push_msat() {
8886                 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8887                 // to_remote output is encumbered by a P2WPKH
8888
8889                 let nodes = create_network(2);
8890
8891                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8892                 nodes[0].node.force_close_channel(&chan.2);
8893                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8894                 match events[0] {
8895                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8896                         _ => panic!("Unexpected event"),
8897                 }
8898                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8899                 assert_eq!(node_txn.len(), 1);
8900                 check_spends!(node_txn[0], chan.3.clone());
8901                 assert_eq!(node_txn[0].output.len(), 2); // We can't force trimming of to_remote output as channel_reserve_satoshis block us to do so at channel opening
8902
8903                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8904                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8905                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8906                 match events[0] {
8907                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8908                         _ => panic!("Unexpected event"),
8909                 }
8910                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8911                 assert_eq!(spend_txn.len(), 2);
8912                 assert_eq!(spend_txn[0], spend_txn[1]);
8913                 check_spends!(spend_txn[0], node_txn[0].clone());
8914         }
8915
8916         #[test]
8917         fn test_claim_on_remote_revoked_sizeable_push_msat() {
8918                 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8919                 // to_remote output is encumbered by a P2WPKH
8920
8921                 let nodes = create_network(2);
8922
8923                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
8924                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8925                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
8926                 assert_eq!(revoked_local_txn[0].input.len(), 1);
8927                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8928
8929                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8930                 let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8931                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
8932                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8933                 match events[0] {
8934                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8935                         _ => panic!("Unexpected event"),
8936                 }
8937                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8938                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8939                 assert_eq!(spend_txn.len(), 4);
8940                 assert_eq!(spend_txn[0], spend_txn[2]); // to_remote output on revoked remote commitment_tx
8941                 check_spends!(spend_txn[0], revoked_local_txn[0].clone());
8942                 assert_eq!(spend_txn[1], spend_txn[3]); // to_local output on local commitment tx
8943                 check_spends!(spend_txn[1], node_txn[0].clone());
8944         }
8945
8946         #[test]
8947         fn test_static_spendable_outputs_preimage_tx() {
8948                 let nodes = create_network(2);
8949
8950                 // Create some initial channels
8951                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8952
8953                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8954
8955                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8956                 assert_eq!(commitment_tx[0].input.len(), 1);
8957                 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
8958
8959                 // Settle A's commitment tx on B's chain
8960                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8961                 assert!(nodes[1].node.claim_funds(payment_preimage));
8962                 check_added_monitors!(nodes[1], 1);
8963                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
8964                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8965                 match events[0] {
8966                         MessageSendEvent::UpdateHTLCs { .. } => {},
8967                         _ => panic!("Unexpected event"),
8968                 }
8969                 match events[1] {
8970                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8971                         _ => panic!("Unexepected event"),
8972                 }
8973
8974                 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
8975                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 1 (local commitment tx), ChannelMonitor: 2 (1 preimage tx) * 2 (block-rescan)
8976                 check_spends!(node_txn[0], commitment_tx[0].clone());
8977                 assert_eq!(node_txn[0], node_txn[2]);
8978                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8979                 check_spends!(node_txn[1], chan_1.3.clone());
8980
8981                 let spend_txn = check_spendable_outputs!(nodes[1], 1); // , 0, 0, 1, 1);
8982                 assert_eq!(spend_txn.len(), 2);
8983                 assert_eq!(spend_txn[0], spend_txn[1]);
8984                 check_spends!(spend_txn[0], node_txn[0].clone());
8985         }
8986
8987         #[test]
8988         fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
8989                 let nodes = create_network(2);
8990
8991                 // Create some initial channels
8992                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8993
8994                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8995                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
8996                 assert_eq!(revoked_local_txn[0].input.len(), 1);
8997                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
8998
8999                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9000
9001                 let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9002                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9003                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9004                 match events[0] {
9005                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9006                         _ => panic!("Unexpected event"),
9007                 }
9008                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9009                 assert_eq!(node_txn.len(), 3);
9010                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]);
9011                 assert_eq!(node_txn[0].input.len(), 2);
9012                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
9013
9014                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9015                 assert_eq!(spend_txn.len(), 2);
9016                 assert_eq!(spend_txn[0], spend_txn[1]);
9017                 check_spends!(spend_txn[0], node_txn[0].clone());
9018         }
9019
9020         #[test]
9021         fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
9022                 let nodes = create_network(2);
9023
9024                 // Create some initial channels
9025                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9026
9027                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9028                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9029                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9030                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9031
9032                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9033
9034                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9035                 // A will generate HTLC-Timeout from revoked commitment tx
9036                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9037                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9038                 match events[0] {
9039                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9040                         _ => panic!("Unexpected event"),
9041                 }
9042                 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9043                 assert_eq!(revoked_htlc_txn.len(), 3);
9044                 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
9045                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
9046                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9047                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
9048                 check_spends!(revoked_htlc_txn[1], chan_1.3.clone());
9049
9050                 // B will generate justice tx from A's revoked commitment/HTLC tx
9051                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
9052                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9053                 match events[0] {
9054                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9055                         _ => panic!("Unexpected event"),
9056                 }
9057
9058                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9059                 assert_eq!(node_txn.len(), 4);
9060                 assert_eq!(node_txn[3].input.len(), 1);
9061                 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
9062
9063                 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
9064                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9065                 assert_eq!(spend_txn.len(), 3);
9066                 assert_eq!(spend_txn[0], spend_txn[1]);
9067                 check_spends!(spend_txn[0], node_txn[0].clone());
9068                 check_spends!(spend_txn[2], node_txn[3].clone());
9069         }
9070
9071         #[test]
9072         fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
9073                 let nodes = create_network(2);
9074
9075                 // Create some initial channels
9076                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9077
9078                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9079                 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9080                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9081                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9082
9083                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9084
9085                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9086                 // B will generate HTLC-Success from revoked commitment tx
9087                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9088                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9089                 match events[0] {
9090                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9091                         _ => panic!("Unexpected event"),
9092                 }
9093                 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9094
9095                 assert_eq!(revoked_htlc_txn.len(), 3);
9096                 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
9097                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
9098                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9099                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
9100
9101                 // A will generate justice tx from B's revoked commitment/HTLC tx
9102                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
9103                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9104                 match events[0] {
9105                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9106                         _ => panic!("Unexpected event"),
9107                 }
9108
9109                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9110                 assert_eq!(node_txn.len(), 4);
9111                 assert_eq!(node_txn[3].input.len(), 1);
9112                 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
9113
9114                 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
9115                 let spend_txn = check_spendable_outputs!(nodes[0], 1);
9116                 assert_eq!(spend_txn.len(), 5);
9117                 assert_eq!(spend_txn[0], spend_txn[2]);
9118                 assert_eq!(spend_txn[1], spend_txn[3]);
9119                 check_spends!(spend_txn[0], revoked_local_txn[0].clone()); // spending to_remote output from revoked local tx
9120                 check_spends!(spend_txn[1], node_txn[2].clone()); // spending justice tx output from revoked local tx htlc received output
9121                 check_spends!(spend_txn[4], node_txn[3].clone()); // spending justice tx output on htlc success tx
9122         }
9123
9124         #[test]
9125         fn test_onchain_to_onchain_claim() {
9126                 // Test that in case of channel closure, we detect the state of output thanks to
9127                 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
9128                 // First, have C claim an HTLC against its own latest commitment transaction.
9129                 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
9130                 // channel.
9131                 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
9132                 // gets broadcast.
9133
9134                 let nodes = create_network(3);
9135
9136                 // Create some initial channels
9137                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9138                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
9139
9140                 // Rebalance the network a bit by relaying one payment through all the channels ...
9141                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
9142                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
9143
9144                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
9145                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9146                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
9147                 check_spends!(commitment_tx[0], chan_2.3.clone());
9148                 nodes[2].node.claim_funds(payment_preimage);
9149                 check_added_monitors!(nodes[2], 1);
9150                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9151                 assert!(updates.update_add_htlcs.is_empty());
9152                 assert!(updates.update_fail_htlcs.is_empty());
9153                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
9154                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9155
9156                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
9157                 let events = nodes[2].node.get_and_clear_pending_msg_events();
9158                 assert_eq!(events.len(), 1);
9159                 match events[0] {
9160                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9161                         _ => panic!("Unexpected event"),
9162                 }
9163
9164                 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
9165                 assert_eq!(c_txn.len(), 3);
9166                 assert_eq!(c_txn[0], c_txn[2]);
9167                 assert_eq!(commitment_tx[0], c_txn[1]);
9168                 check_spends!(c_txn[1], chan_2.3.clone());
9169                 check_spends!(c_txn[2], c_txn[1].clone());
9170                 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
9171                 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9172                 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
9173                 assert_eq!(c_txn[0].lock_time, 0); // Success tx
9174
9175                 // 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
9176                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
9177                 {
9178                         let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9179                         assert_eq!(b_txn.len(), 4);
9180                         assert_eq!(b_txn[0], b_txn[3]);
9181                         check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
9182                         check_spends!(b_txn[2], b_txn[1].clone()); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
9183                         assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9184                         assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
9185                         assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
9186                         check_spends!(b_txn[0], c_txn[1].clone()); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
9187                         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9188                         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
9189                         assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
9190                         b_txn.clear();
9191                 }
9192                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
9193                 check_added_monitors!(nodes[1], 1);
9194                 match msg_events[0] {
9195                         MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
9196                         _ => panic!("Unexpected event"),
9197                 }
9198                 match msg_events[1] {
9199                         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, .. } } => {
9200                                 assert!(update_add_htlcs.is_empty());
9201                                 assert!(update_fail_htlcs.is_empty());
9202                                 assert_eq!(update_fulfill_htlcs.len(), 1);
9203                                 assert!(update_fail_malformed_htlcs.is_empty());
9204                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
9205                         },
9206                         _ => panic!("Unexpected event"),
9207                 };
9208                 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
9209                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9210                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
9211                 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9212                 assert_eq!(b_txn.len(), 3);
9213                 check_spends!(b_txn[1], chan_1.3); // Local commitment tx, issued by ChannelManager
9214                 assert_eq!(b_txn[0], b_txn[2]); // HTLC-Success tx, issued by ChannelMonitor, * 2 due to block rescan
9215                 check_spends!(b_txn[0], commitment_tx[0].clone());
9216                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9217                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
9218                 assert_eq!(b_txn[2].lock_time, 0); // Success tx
9219                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
9220                 match msg_events[0] {
9221                         MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
9222                         _ => panic!("Unexpected event"),
9223                 }
9224         }
9225
9226         #[test]
9227         fn test_duplicate_payment_hash_one_failure_one_success() {
9228                 // Topology : A --> B --> C
9229                 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
9230                 let mut nodes = create_network(3);
9231
9232                 create_announced_chan_between_nodes(&nodes, 0, 1);
9233                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
9234
9235                 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
9236                 *nodes[0].network_payment_count.borrow_mut() -= 1;
9237                 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
9238
9239                 let commitment_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
9240                 assert_eq!(commitment_txn[0].input.len(), 1);
9241                 check_spends!(commitment_txn[0], chan_2.3.clone());
9242
9243                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9244                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
9245                 let htlc_timeout_tx;
9246                 { // Extract one of the two HTLC-Timeout transaction
9247                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9248                         assert_eq!(node_txn.len(), 7);
9249                         assert_eq!(node_txn[0], node_txn[5]);
9250                         assert_eq!(node_txn[1], node_txn[6]);
9251                         check_spends!(node_txn[0], commitment_txn[0].clone());
9252                         assert_eq!(node_txn[0].input.len(), 1);
9253                         check_spends!(node_txn[1], commitment_txn[0].clone());
9254                         assert_eq!(node_txn[1].input.len(), 1);
9255                         assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
9256                         check_spends!(node_txn[2], chan_2.3.clone());
9257                         check_spends!(node_txn[3], node_txn[2].clone());
9258                         check_spends!(node_txn[4], node_txn[2].clone());
9259                         htlc_timeout_tx = node_txn[1].clone();
9260                 }
9261
9262                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9263                 match events[0] {
9264                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9265                         _ => panic!("Unexepected event"),
9266                 }
9267
9268                 nodes[2].node.claim_funds(our_payment_preimage);
9269                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
9270                 check_added_monitors!(nodes[2], 2);
9271                 let events = nodes[2].node.get_and_clear_pending_msg_events();
9272                 match events[0] {
9273                         MessageSendEvent::UpdateHTLCs { .. } => {},
9274                         _ => panic!("Unexpected event"),
9275                 }
9276                 match events[1] {
9277                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9278                         _ => panic!("Unexepected event"),
9279                 }
9280                 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9281                 assert_eq!(htlc_success_txn.len(), 5);
9282                 check_spends!(htlc_success_txn[2], chan_2.3.clone());
9283                 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
9284                 assert_eq!(htlc_success_txn[0].input.len(), 1);
9285                 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9286                 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
9287                 assert_eq!(htlc_success_txn[1].input.len(), 1);
9288                 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9289                 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
9290                 check_spends!(htlc_success_txn[0], commitment_txn[0].clone());
9291                 check_spends!(htlc_success_txn[1], commitment_txn[0].clone());
9292
9293                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
9294                 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9295                 assert!(htlc_updates.update_add_htlcs.is_empty());
9296                 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
9297                 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
9298                 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
9299                 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
9300                 check_added_monitors!(nodes[1], 1);
9301
9302                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]).unwrap();
9303                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9304                 {
9305                         commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
9306                         let events = nodes[0].node.get_and_clear_pending_msg_events();
9307                         assert_eq!(events.len(), 1);
9308                         match events[0] {
9309                                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
9310                                 },
9311                                 _ => { panic!("Unexpected event"); }
9312                         }
9313                 }
9314                 let events = nodes[0].node.get_and_clear_pending_events();
9315                 match events[0] {
9316                         Event::PaymentFailed { ref payment_hash, .. } => {
9317                                 assert_eq!(*payment_hash, duplicate_payment_hash);
9318                         }
9319                         _ => panic!("Unexpected event"),
9320                 }
9321
9322                 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
9323                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
9324                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9325                 assert!(updates.update_add_htlcs.is_empty());
9326                 assert!(updates.update_fail_htlcs.is_empty());
9327                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
9328                 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
9329                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9330                 check_added_monitors!(nodes[1], 1);
9331
9332                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
9333                 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
9334
9335                 let events = nodes[0].node.get_and_clear_pending_events();
9336                 match events[0] {
9337                         Event::PaymentSent { ref payment_preimage } => {
9338                                 assert_eq!(*payment_preimage, our_payment_preimage);
9339                         }
9340                         _ => panic!("Unexpected event"),
9341                 }
9342         }
9343
9344         #[test]
9345         fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
9346                 let nodes = create_network(2);
9347
9348                 // Create some initial channels
9349                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9350
9351                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
9352                 let local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9353                 assert_eq!(local_txn[0].input.len(), 1);
9354                 check_spends!(local_txn[0], chan_1.3.clone());
9355
9356                 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
9357                 nodes[1].node.claim_funds(payment_preimage);
9358                 check_added_monitors!(nodes[1], 1);
9359                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9360                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
9361                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9362                 match events[0] {
9363                         MessageSendEvent::UpdateHTLCs { .. } => {},
9364                         _ => panic!("Unexpected event"),
9365                 }
9366                 match events[1] {
9367                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9368                         _ => panic!("Unexepected event"),
9369                 }
9370                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9371                 assert_eq!(node_txn[0].input.len(), 1);
9372                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9373                 check_spends!(node_txn[0], local_txn[0].clone());
9374
9375                 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
9376                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9377                 assert_eq!(spend_txn.len(), 2);
9378                 check_spends!(spend_txn[0], node_txn[0].clone());
9379                 check_spends!(spend_txn[1], node_txn[2].clone());
9380         }
9381
9382         #[test]
9383         fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
9384                 let nodes = create_network(2);
9385
9386                 // Create some initial channels
9387                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9388
9389                 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
9390                 let local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9391                 assert_eq!(local_txn[0].input.len(), 1);
9392                 check_spends!(local_txn[0], chan_1.3.clone());
9393
9394                 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
9395                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9396                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
9397                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9398                 match events[0] {
9399                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9400                         _ => panic!("Unexepected event"),
9401                 }
9402                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9403                 assert_eq!(node_txn[0].input.len(), 1);
9404                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9405                 check_spends!(node_txn[0], local_txn[0].clone());
9406
9407                 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
9408                 let spend_txn = check_spendable_outputs!(nodes[0], 1);
9409                 assert_eq!(spend_txn.len(), 8);
9410                 assert_eq!(spend_txn[0], spend_txn[2]);
9411                 assert_eq!(spend_txn[0], spend_txn[4]);
9412                 assert_eq!(spend_txn[0], spend_txn[6]);
9413                 assert_eq!(spend_txn[1], spend_txn[3]);
9414                 assert_eq!(spend_txn[1], spend_txn[5]);
9415                 assert_eq!(spend_txn[1], spend_txn[7]);
9416                 check_spends!(spend_txn[0], local_txn[0].clone());
9417                 check_spends!(spend_txn[1], node_txn[0].clone());
9418         }
9419
9420         #[test]
9421         fn test_static_output_closing_tx() {
9422                 let nodes = create_network(2);
9423
9424                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
9425
9426                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
9427                 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
9428
9429                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9430                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
9431                 let spend_txn = check_spendable_outputs!(nodes[0], 2);
9432                 assert_eq!(spend_txn.len(), 1);
9433                 check_spends!(spend_txn[0], closing_tx.clone());
9434
9435                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
9436                 let spend_txn = check_spendable_outputs!(nodes[1], 2);
9437                 assert_eq!(spend_txn.len(), 1);
9438                 check_spends!(spend_txn[0], closing_tx);
9439         }
9440
9441         fn run_onion_failure_test<F1,F2>(_name: &str, test_case: u8, nodes: &Vec<Node>, route: &Route, payment_hash: &PaymentHash, callback_msg: F1, callback_node: F2, expected_retryable: bool, expected_error_code: Option<u16>, expected_channel_update: Option<HTLCFailChannelUpdate>)
9442                 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
9443                                         F2: FnMut(),
9444         {
9445                 run_onion_failure_test_with_fail_intercept(_name, test_case, nodes, route, payment_hash, callback_msg, |_|{}, callback_node, expected_retryable, expected_error_code, expected_channel_update);
9446         }
9447
9448         // test_case
9449         // 0: node1 fail backward
9450         // 1: final node fail backward
9451         // 2: payment completed but the user reject the payment
9452         // 3: final node fail backward (but tamper onion payloads from node0)
9453         // 100: trigger error in the intermediate node and tamper returnning fail_htlc
9454         // 200: trigger error in the final node and tamper returnning fail_htlc
9455         fn run_onion_failure_test_with_fail_intercept<F1,F2,F3>(_name: &str, test_case: u8, nodes: &Vec<Node>, route: &Route, payment_hash: &PaymentHash, mut callback_msg: F1, mut callback_fail: F2, mut callback_node: F3, expected_retryable: bool, expected_error_code: Option<u16>, expected_channel_update: Option<HTLCFailChannelUpdate>)
9456                 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
9457                                         F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
9458                                         F3: FnMut(),
9459         {
9460                 use ln::msgs::HTLCFailChannelUpdate;
9461
9462                 // reset block height
9463                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9464                 for ix in 0..nodes.len() {
9465                         nodes[ix].chain_monitor.block_connected_checked(&header, 1, &Vec::new()[..], &[0; 0]);
9466                 }
9467
9468                 macro_rules! expect_event {
9469                         ($node: expr, $event_type: path) => {{
9470                                 let events = $node.node.get_and_clear_pending_events();
9471                                 assert_eq!(events.len(), 1);
9472                                 match events[0] {
9473                                         $event_type { .. } => {},
9474                                         _ => panic!("Unexpected event"),
9475                                 }
9476                         }}
9477                 }
9478
9479                 macro_rules! expect_htlc_forward {
9480                         ($node: expr) => {{
9481                                 expect_event!($node, Event::PendingHTLCsForwardable);
9482                                 $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
9483                                 $node.node.process_pending_htlc_forwards();
9484                         }}
9485                 }
9486
9487                 // 0 ~~> 2 send payment
9488                 nodes[0].node.send_payment(route.clone(), payment_hash.clone()).unwrap();
9489                 check_added_monitors!(nodes[0], 1);
9490                 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
9491                 // temper update_add (0 => 1)
9492                 let mut update_add_0 = update_0.update_add_htlcs[0].clone();
9493                 if test_case == 0 || test_case == 3 || test_case == 100 {
9494                         callback_msg(&mut update_add_0);
9495                         callback_node();
9496                 }
9497                 // 0 => 1 update_add & CS
9498                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0).unwrap();
9499                 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
9500
9501                 let update_1_0 = match test_case {
9502                         0|100 => { // intermediate node failure; fail backward to 0
9503                                 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9504                                 assert!(update_1_0.update_fail_htlcs.len()+update_1_0.update_fail_malformed_htlcs.len()==1 && (update_1_0.update_fail_htlcs.len()==1 || update_1_0.update_fail_malformed_htlcs.len()==1));
9505                                 update_1_0
9506                         },
9507                         1|2|3|200 => { // final node failure; forwarding to 2
9508                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9509                                 // forwarding on 1
9510                                 if test_case != 200 {
9511                                         callback_node();
9512                                 }
9513                                 expect_htlc_forward!(&nodes[1]);
9514
9515                                 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
9516                                 check_added_monitors!(&nodes[1], 1);
9517                                 assert_eq!(update_1.update_add_htlcs.len(), 1);
9518                                 // tamper update_add (1 => 2)
9519                                 let mut update_add_1 = update_1.update_add_htlcs[0].clone();
9520                                 if test_case != 3 && test_case != 200 {
9521                                         callback_msg(&mut update_add_1);
9522                                 }
9523
9524                                 // 1 => 2
9525                                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1).unwrap();
9526                                 commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
9527
9528                                 if test_case == 2 || test_case == 200 {
9529                                         expect_htlc_forward!(&nodes[2]);
9530                                         expect_event!(&nodes[2], Event::PaymentReceived);
9531                                         callback_node();
9532                                 }
9533
9534                                 let update_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9535                                 if test_case == 2 || test_case == 200 {
9536                                         check_added_monitors!(&nodes[2], 1);
9537                                 }
9538                                 assert!(update_2_1.update_fail_htlcs.len() == 1);
9539
9540                                 let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
9541                                 if test_case == 200 {
9542                                         callback_fail(&mut fail_msg);
9543                                 }
9544
9545                                 // 2 => 1
9546                                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg).unwrap();
9547                                 commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true, true);
9548
9549                                 // backward fail on 1
9550                                 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9551                                 assert!(update_1_0.update_fail_htlcs.len() == 1);
9552                                 update_1_0
9553                         },
9554                         _ => unreachable!(),
9555                 };
9556
9557                 // 1 => 0 commitment_signed_dance
9558                 if update_1_0.update_fail_htlcs.len() > 0 {
9559                         let mut fail_msg = update_1_0.update_fail_htlcs[0].clone();
9560                         if test_case == 100 {
9561                                 callback_fail(&mut fail_msg);
9562                         }
9563                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg).unwrap();
9564                 } else {
9565                         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]).unwrap();
9566                 };
9567
9568                 commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
9569
9570                 let events = nodes[0].node.get_and_clear_pending_events();
9571                 assert_eq!(events.len(), 1);
9572                 if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code } = &events[0] {
9573                         assert_eq!(*rejected_by_dest, !expected_retryable);
9574                         assert_eq!(*error_code, expected_error_code);
9575                 } else {
9576                         panic!("Uexpected event");
9577                 }
9578
9579                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9580                 if expected_channel_update.is_some() {
9581                         assert_eq!(events.len(), 1);
9582                         match events[0] {
9583                                 MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
9584                                         match update {
9585                                                 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {
9586                                                         if let HTLCFailChannelUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
9587                                                                 panic!("channel_update not found!");
9588                                                         }
9589                                                 },
9590                                                 &HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
9591                                                         if let HTLCFailChannelUpdate::ChannelClosed { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
9592                                                                 assert!(*short_channel_id == *expected_short_channel_id);
9593                                                                 assert!(*is_permanent == *expected_is_permanent);
9594                                                         } else {
9595                                                                 panic!("Unexpected message event");
9596                                                         }
9597                                                 },
9598                                                 &HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
9599                                                         if let HTLCFailChannelUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
9600                                                                 assert!(*node_id == *expected_node_id);
9601                                                                 assert!(*is_permanent == *expected_is_permanent);
9602                                                         } else {
9603                                                                 panic!("Unexpected message event");
9604                                                         }
9605                                                 },
9606                                         }
9607                                 },
9608                                 _ => panic!("Unexpected message event"),
9609                         }
9610                 } else {
9611                         assert_eq!(events.len(), 0);
9612                 }
9613         }
9614
9615         impl msgs::ChannelUpdate {
9616                 fn dummy() -> msgs::ChannelUpdate {
9617                         use secp256k1::ffi::Signature as FFISignature;
9618                         use secp256k1::Signature;
9619                         msgs::ChannelUpdate {
9620                                 signature: Signature::from(FFISignature::new()),
9621                                 contents: msgs::UnsignedChannelUpdate {
9622                                         chain_hash: Sha256dHash::from_data(&vec![0u8][..]),
9623                                         short_channel_id: 0,
9624                                         timestamp: 0,
9625                                         flags: 0,
9626                                         cltv_expiry_delta: 0,
9627                                         htlc_minimum_msat: 0,
9628                                         fee_base_msat: 0,
9629                                         fee_proportional_millionths: 0,
9630                                         excess_data: vec![],
9631                                 }
9632                         }
9633                 }
9634         }
9635
9636         #[test]
9637         fn test_onion_failure() {
9638                 use ln::msgs::ChannelUpdate;
9639                 use ln::channelmanager::CLTV_FAR_FAR_AWAY;
9640                 use secp256k1;
9641
9642                 const BADONION: u16 = 0x8000;
9643                 const PERM: u16 = 0x4000;
9644                 const NODE: u16 = 0x2000;
9645                 const UPDATE: u16 = 0x1000;
9646
9647                 let mut nodes = create_network(3);
9648                 for node in nodes.iter() {
9649                         *node.keys_manager.override_session_priv.lock().unwrap() = Some(SecretKey::from_slice(&Secp256k1::without_caps(), &[3; 32]).unwrap());
9650                 }
9651                 let channels = [create_announced_chan_between_nodes(&nodes, 0, 1), create_announced_chan_between_nodes(&nodes, 1, 2)];
9652                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
9653                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap();
9654                 // positve case
9655                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000);
9656
9657                 // intermediate node failure
9658                 run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, |msg| {
9659                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9660                         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
9661                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9662                         let (mut onion_payloads, _htlc_msat, _htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height).unwrap();
9663                         onion_payloads[0].realm = 3;
9664                         msg.onion_routing_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
9665                 }, ||{}, true, Some(PERM|1), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));//XXX incremented channels idx here
9666
9667                 // final node failure
9668                 run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, |msg| {
9669                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9670                         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
9671                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9672                         let (mut onion_payloads, _htlc_msat, _htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height).unwrap();
9673                         onion_payloads[1].realm = 3;
9674                         msg.onion_routing_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
9675                 }, ||{}, false, Some(PERM|1), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
9676
9677                 // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
9678                 // receiving simulated fail messages
9679                 // intermediate node failure
9680                 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
9681                         // trigger error
9682                         msg.amount_msat -= 1;
9683                 }, |msg| {
9684                         // and tamper returing error message
9685                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9686                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9687                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], NODE|2, &[0;0]);
9688                 }, ||{}, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: false}));
9689
9690                 // final node failure
9691                 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
9692                         // and tamper returing error message
9693                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9694                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9695                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], NODE|2, &[0;0]);
9696                 }, ||{
9697                         nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
9698                 }, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: false}));
9699
9700                 // intermediate node failure
9701                 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
9702                         msg.amount_msat -= 1;
9703                 }, |msg| {
9704                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9705                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9706                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|2, &[0;0]);
9707                 }, ||{}, true, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
9708
9709                 // final node failure
9710                 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
9711                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9712                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9713                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|2, &[0;0]);
9714                 }, ||{
9715                         nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
9716                 }, false, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
9717
9718                 // intermediate node failure
9719                 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
9720                         msg.amount_msat -= 1;
9721                 }, |msg| {
9722                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9723                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9724                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|3, &[0;0]);
9725                 }, ||{
9726                         nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
9727                 }, true, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
9728
9729                 // final node failure
9730                 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
9731                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9732                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9733                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|3, &[0;0]);
9734                 }, ||{
9735                         nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
9736                 }, false, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
9737
9738                 run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
9739                         Some(BADONION|PERM|4), None);
9740
9741                 run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
9742                         Some(BADONION|PERM|5), None);
9743
9744                 run_onion_failure_test("invalid_onion_key", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.public_key = Err(secp256k1::Error::InvalidPublicKey);}, ||{}, true,
9745                         Some(BADONION|PERM|6), None);
9746
9747                 run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
9748                         msg.amount_msat -= 1;
9749                 }, |msg| {
9750                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9751                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9752                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], UPDATE|7, &ChannelUpdate::dummy().encode_with_len()[..]);
9753                 }, ||{}, true, Some(UPDATE|7), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
9754
9755                 run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
9756                         msg.amount_msat -= 1;
9757                 }, |msg| {
9758                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9759                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9760                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|8, &[0;0]);
9761                         // short_channel_id from the processing node
9762                 }, ||{}, true, Some(PERM|8), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
9763
9764                 run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
9765                         msg.amount_msat -= 1;
9766                 }, |msg| {
9767                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9768                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9769                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|9, &[0;0]);
9770                         // short_channel_id from the processing node
9771                 }, ||{}, true, Some(PERM|9), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
9772
9773                 let mut bogus_route = route.clone();
9774                 bogus_route.hops[1].short_channel_id -= 1;
9775                 run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(PERM|10),
9776                   Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: bogus_route.hops[1].short_channel_id, is_permanent:true}));
9777
9778                 let amt_to_forward = nodes[1].node.channel_state.lock().unwrap().by_id.get(&channels[1].2).unwrap().get_their_htlc_minimum_msat() - 1;
9779                 let mut bogus_route = route.clone();
9780                 let route_len = bogus_route.hops.len();
9781                 bogus_route.hops[route_len-1].fee_msat = amt_to_forward;
9782                 run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(UPDATE|11), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
9783
9784                 //TODO: with new config API, we will be able to generate both valid and
9785                 //invalid channel_update cases.
9786                 run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, |msg| {
9787                         msg.amount_msat -= 1;
9788                 }, || {}, true, Some(UPDATE|12), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
9789
9790                 run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, |msg| {
9791                         // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
9792                         msg.cltv_expiry -= 1;
9793                 }, || {}, true, Some(UPDATE|13), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
9794
9795                 run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, |msg| {
9796                         let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - HTLC_FAIL_TIMEOUT_BLOCKS + 1;
9797                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9798                         nodes[1].chain_monitor.block_connected_checked(&header, height, &Vec::new()[..], &[0; 0]);
9799                 }, ||{}, true, Some(UPDATE|14), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
9800
9801                 run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, |_| {}, || {
9802                         nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
9803                 }, false, Some(PERM|15), None);
9804
9805                 run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, |msg| {
9806                         let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - HTLC_FAIL_TIMEOUT_BLOCKS + 1;
9807                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9808                         nodes[2].chain_monitor.block_connected_checked(&header, height, &Vec::new()[..], &[0; 0]);
9809                 }, || {}, true, Some(17), None);
9810
9811                 run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, |_| {}, || {
9812                         for (_, mut pending_forwards) in nodes[1].node.channel_state.lock().unwrap().borrow_parts().forward_htlcs.iter_mut() {
9813                                 for f in pending_forwards.iter_mut() {
9814                                         f.forward_info.outgoing_cltv_value += 1;
9815                                 }
9816                         }
9817                 }, true, Some(18), None);
9818
9819                 run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, |_| {}, || {
9820                         // violate amt_to_forward > msg.amount_msat
9821                         for (_, mut pending_forwards) in nodes[1].node.channel_state.lock().unwrap().borrow_parts().forward_htlcs.iter_mut() {
9822                                 for f in pending_forwards.iter_mut() {
9823                                         f.forward_info.amt_to_forward -= 1;
9824                                 }
9825                         }
9826                 }, true, Some(19), None);
9827
9828                 run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, |_| {}, || {
9829                         // disconnect event to the channel between nodes[1] ~ nodes[2]
9830                         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9831                         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9832                 }, true, Some(UPDATE|20), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
9833                 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9834
9835                 run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, |msg| {
9836                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9837                         let mut route = route.clone();
9838                         let height = 1;
9839                         route.hops[1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.hops[0].cltv_expiry_delta + 1;
9840                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9841                         let (onion_payloads, _, htlc_cltv) = ChannelManager::build_onion_payloads(&route, height).unwrap();
9842                         let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
9843                         msg.cltv_expiry = htlc_cltv;
9844                         msg.onion_routing_packet = onion_packet;
9845                 }, ||{}, true, Some(21), None);
9846         }
9847 }