Use bitcoin_hashes' fixed_time_eq, removing the rust-crypto dep
[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 use bitcoin_hashes::cmp::fixed_time_eq;
21
22 use secp256k1::key::{SecretKey,PublicKey};
23 use secp256k1::{Secp256k1,Message};
24 use secp256k1::ecdh::SharedSecret;
25 use secp256k1;
26
27 use chain::chaininterface::{BroadcasterInterface,ChainListener,ChainWatchInterface,FeeEstimator};
28 use chain::transaction::OutPoint;
29 use ln::channel::{Channel, ChannelError};
30 use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, ManyChannelMonitor, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, HTLC_FAIL_ANTI_REORG_DELAY};
31 use ln::router::{Route,RouteHop};
32 use ln::msgs;
33 use ln::msgs::{ChannelMessageHandler, DecodeError, HandleError};
34 use chain::keysinterface::KeysInterface;
35 use util::config::UserConfig;
36 use util::{byte_utils, events, internal_traits, rng};
37 use util::ser::{Readable, ReadableArgs, Writeable, Writer};
38 use util::chacha20::ChaCha20;
39 use util::logger::Logger;
40 use util::errors::APIError;
41 use util::errors;
42
43 use std::{cmp, ptr, mem};
44 use std::collections::{HashMap, hash_map, HashSet};
45 use std::io::Cursor;
46 use std::sync::{Arc, Mutex, MutexGuard, RwLock};
47 use std::sync::atomic::{AtomicUsize, Ordering};
48 use std::time::{Instant,Duration};
49
50 /// We hold various information about HTLC relay in the HTLC objects in Channel itself:
51 ///
52 /// Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
53 /// forward the HTLC with information it will give back to us when it does so, or if it should Fail
54 /// the HTLC with the relevant message for the Channel to handle giving to the remote peer.
55 ///
56 /// When a Channel forwards an HTLC to its peer, it will give us back the PendingForwardHTLCInfo
57 /// which we will use to construct an outbound HTLC, with a relevant HTLCSource::PreviousHopData
58 /// filled in to indicate where it came from (which we can use to either fail-backwards or fulfill
59 /// the HTLC backwards along the relevant path).
60 /// Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
61 /// our payment, which we can use to decode errors or inform the user that the payment was sent.
62 mod channel_held_info {
63         use ln::msgs;
64         use ln::router::Route;
65         use ln::channelmanager::PaymentHash;
66         use secp256k1::key::SecretKey;
67
68         /// Stores the info we will need to send when we want to forward an HTLC onwards
69         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
70         pub struct PendingForwardHTLCInfo {
71                 pub(super) onion_packet: Option<msgs::OnionPacket>,
72                 pub(super) incoming_shared_secret: [u8; 32],
73                 pub(super) payment_hash: PaymentHash,
74                 pub(super) short_channel_id: u64,
75                 pub(super) amt_to_forward: u64,
76                 pub(super) outgoing_cltv_value: u32,
77         }
78
79         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
80         pub enum HTLCFailureMsg {
81                 Relay(msgs::UpdateFailHTLC),
82                 Malformed(msgs::UpdateFailMalformedHTLC),
83         }
84
85         /// Stores whether we can't forward an HTLC or relevant forwarding info
86         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
87         pub enum PendingHTLCStatus {
88                 Forward(PendingForwardHTLCInfo),
89                 Fail(HTLCFailureMsg),
90         }
91
92         /// Tracks the inbound corresponding to an outbound HTLC
93         #[derive(Clone, PartialEq)]
94         pub struct HTLCPreviousHopData {
95                 pub(super) short_channel_id: u64,
96                 pub(super) htlc_id: u64,
97                 pub(super) incoming_packet_shared_secret: [u8; 32],
98         }
99
100         /// Tracks the inbound corresponding to an outbound HTLC
101         #[derive(Clone, PartialEq)]
102         pub enum HTLCSource {
103                 PreviousHopData(HTLCPreviousHopData),
104                 OutboundRoute {
105                         route: Route,
106                         session_priv: SecretKey,
107                         /// Technically we can recalculate this from the route, but we cache it here to avoid
108                         /// doing a double-pass on route when we get a failure back
109                         first_hop_htlc_msat: u64,
110                 },
111         }
112         #[cfg(test)]
113         impl HTLCSource {
114                 pub fn dummy() -> Self {
115                         HTLCSource::OutboundRoute {
116                                 route: Route { hops: Vec::new() },
117                                 session_priv: SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[1; 32]).unwrap(),
118                                 first_hop_htlc_msat: 0,
119                         }
120                 }
121         }
122
123         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
124         pub(crate) enum HTLCFailReason {
125                 ErrorPacket {
126                         err: msgs::OnionErrorPacket,
127                 },
128                 Reason {
129                         failure_code: u16,
130                         data: Vec<u8>,
131                 }
132         }
133 }
134 pub(super) use self::channel_held_info::*;
135
136 /// payment_hash type, use to cross-lock hop
137 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
138 pub struct PaymentHash(pub [u8;32]);
139 /// payment_preimage type, use to route payment between hop
140 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
141 pub struct PaymentPreimage(pub [u8;32]);
142
143 type ShutdownResult = (Vec<Transaction>, Vec<(HTLCSource, PaymentHash)>);
144
145 /// Error type returned across the channel_state mutex boundary. When an Err is generated for a
146 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
147 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
148 /// channel_state lock. We then return the set of things that need to be done outside the lock in
149 /// this struct and call handle_error!() on it.
150
151 struct MsgHandleErrInternal {
152         err: msgs::HandleError,
153         shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
154 }
155 impl MsgHandleErrInternal {
156         #[inline]
157         fn send_err_msg_no_close(err: &'static str, channel_id: [u8; 32]) -> Self {
158                 Self {
159                         err: HandleError {
160                                 err,
161                                 action: Some(msgs::ErrorAction::SendErrorMessage {
162                                         msg: msgs::ErrorMessage {
163                                                 channel_id,
164                                                 data: err.to_string()
165                                         },
166                                 }),
167                         },
168                         shutdown_finish: None,
169                 }
170         }
171         #[inline]
172         fn from_no_close(err: msgs::HandleError) -> Self {
173                 Self { err, shutdown_finish: None }
174         }
175         #[inline]
176         fn from_finish_shutdown(err: &'static str, channel_id: [u8; 32], shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
177                 Self {
178                         err: HandleError {
179                                 err,
180                                 action: Some(msgs::ErrorAction::SendErrorMessage {
181                                         msg: msgs::ErrorMessage {
182                                                 channel_id,
183                                                 data: err.to_string()
184                                         },
185                                 }),
186                         },
187                         shutdown_finish: Some((shutdown_res, channel_update)),
188                 }
189         }
190         #[inline]
191         fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
192                 Self {
193                         err: match err {
194                                 ChannelError::Ignore(msg) => HandleError {
195                                         err: msg,
196                                         action: Some(msgs::ErrorAction::IgnoreError),
197                                 },
198                                 ChannelError::Close(msg) => HandleError {
199                                         err: msg,
200                                         action: Some(msgs::ErrorAction::SendErrorMessage {
201                                                 msg: msgs::ErrorMessage {
202                                                         channel_id,
203                                                         data: msg.to_string()
204                                                 },
205                                         }),
206                                 },
207                         },
208                         shutdown_finish: None,
209                 }
210         }
211 }
212
213 /// We hold back HTLCs we intend to relay for a random interval in the range (this, 5*this). This
214 /// provides some limited amount of privacy. Ideally this would range from somewhere like 1 second
215 /// to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly. We could
216 /// probably increase this significantly.
217 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
218
219 struct HTLCForwardInfo {
220         prev_short_channel_id: u64,
221         prev_htlc_id: u64,
222         forward_info: PendingForwardHTLCInfo,
223 }
224
225 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
226 /// be sent in the order they appear in the return value, however sometimes the order needs to be
227 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
228 /// they were originally sent). In those cases, this enum is also returned.
229 #[derive(Clone, PartialEq)]
230 pub(super) enum RAACommitmentOrder {
231         /// Send the CommitmentUpdate messages first
232         CommitmentFirst,
233         /// Send the RevokeAndACK message first
234         RevokeAndACKFirst,
235 }
236
237 struct ChannelHolder {
238         by_id: HashMap<[u8; 32], Channel>,
239         short_to_id: HashMap<u64, [u8; 32]>,
240         next_forward: Instant,
241         /// short channel id -> forward infos. Key of 0 means payments received
242         /// Note that while this is held in the same mutex as the channels themselves, no consistency
243         /// guarantees are made about there existing a channel with the short id here, nor the short
244         /// ids in the PendingForwardHTLCInfo!
245         forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
246         /// Note that while this is held in the same mutex as the channels themselves, no consistency
247         /// guarantees are made about the channels given here actually existing anymore by the time you
248         /// go to read them!
249         claimable_htlcs: HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
250         /// Messages to send to peers - pushed to in the same lock that they are generated in (except
251         /// for broadcast messages, where ordering isn't as strict).
252         pending_msg_events: Vec<events::MessageSendEvent>,
253 }
254 struct MutChannelHolder<'a> {
255         by_id: &'a mut HashMap<[u8; 32], Channel>,
256         short_to_id: &'a mut HashMap<u64, [u8; 32]>,
257         next_forward: &'a mut Instant,
258         forward_htlcs: &'a mut HashMap<u64, Vec<HTLCForwardInfo>>,
259         claimable_htlcs: &'a mut HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
260         pending_msg_events: &'a mut Vec<events::MessageSendEvent>,
261 }
262 impl ChannelHolder {
263         fn borrow_parts(&mut self) -> MutChannelHolder {
264                 MutChannelHolder {
265                         by_id: &mut self.by_id,
266                         short_to_id: &mut self.short_to_id,
267                         next_forward: &mut self.next_forward,
268                         forward_htlcs: &mut self.forward_htlcs,
269                         claimable_htlcs: &mut self.claimable_htlcs,
270                         pending_msg_events: &mut self.pending_msg_events,
271                 }
272         }
273 }
274
275 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
276 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
277
278 /// Manager which keeps track of a number of channels and sends messages to the appropriate
279 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
280 ///
281 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
282 /// to individual Channels.
283 ///
284 /// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
285 /// all peers during write/read (though does not modify this instance, only the instance being
286 /// serialized). This will result in any channels which have not yet exchanged funding_created (ie
287 /// called funding_transaction_generated for outbound channels).
288 ///
289 /// Note that you can be a bit lazier about writing out ChannelManager than you can be with
290 /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
291 /// returning from ManyChannelMonitor::add_update_monitor, with ChannelManagers, writing updates
292 /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during
293 /// the serialization process). If the deserialized version is out-of-date compared to the
294 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
295 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
296 ///
297 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelManager), which
298 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
299 /// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
300 /// block_connected() to step towards your best block) upon deserialization before using the
301 /// object!
302 pub struct ChannelManager {
303         default_configuration: UserConfig,
304         genesis_hash: Sha256dHash,
305         fee_estimator: Arc<FeeEstimator>,
306         monitor: Arc<ManyChannelMonitor>,
307         chain_monitor: Arc<ChainWatchInterface>,
308         tx_broadcaster: Arc<BroadcasterInterface>,
309
310         latest_block_height: AtomicUsize,
311         last_block_hash: Mutex<Sha256dHash>,
312         secp_ctx: Secp256k1<secp256k1::All>,
313
314         channel_state: Mutex<ChannelHolder>,
315         our_network_key: SecretKey,
316
317         pending_events: Mutex<Vec<events::Event>>,
318         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
319         /// Essentially just when we're serializing ourselves out.
320         /// Taken first everywhere where we are making changes before any other locks.
321         total_consistency_lock: RwLock<()>,
322
323         keys_manager: Arc<KeysInterface>,
324
325         logger: Arc<Logger>,
326 }
327
328 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
329 /// HTLC's CLTV. This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
330 /// ie the node we forwarded the payment on to should always have enough room to reliably time out
331 /// the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
332 /// CLTV_CLAIM_BUFFER point (we static assert that its at least 3 blocks more).
333 const CLTV_EXPIRY_DELTA: u16 = 6 * 12; //TODO?
334 const CLTV_FAR_FAR_AWAY: u32 = 6 * 24 * 7; //TODO?
335
336 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + 2*HTLC_FAIL_TIMEOUT_BLOCKS +
337 // HTLC_FAIL_ANTI_REORG_DELAY, ie that if the next-hop peer fails the HTLC within
338 // HTLC_FAIL_TIMEOUT_BLOCKS then we'll still have HTLC_FAIL_TIMEOUT_BLOCKS left to fail it
339 // backwards ourselves before hitting the CLTV_CLAIM_BUFFER point and failing the channel
340 // on-chain to time out the HTLC.
341 #[deny(const_err)]
342 #[allow(dead_code)]
343 const CHECK_CLTV_EXPIRY_SANITY: u32 = CLTV_EXPIRY_DELTA as u32 - 2*HTLC_FAIL_TIMEOUT_BLOCKS - CLTV_CLAIM_BUFFER - HTLC_FAIL_ANTI_REORG_DELAY;
344
345 // Check for ability of an attacker to make us fail on-chain by delaying inbound claim. See
346 // ChannelMontior::would_broadcast_at_height for a description of why this is needed.
347 #[deny(const_err)]
348 #[allow(dead_code)]
349 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = CLTV_EXPIRY_DELTA as u32 - HTLC_FAIL_TIMEOUT_BLOCKS - 2*CLTV_CLAIM_BUFFER;
350
351 macro_rules! secp_call {
352         ( $res: expr, $err: expr ) => {
353                 match $res {
354                         Ok(key) => key,
355                         Err(_) => return Err($err),
356                 }
357         };
358 }
359
360 struct OnionKeys {
361         #[cfg(test)]
362         shared_secret: SharedSecret,
363         #[cfg(test)]
364         blinding_factor: [u8; 32],
365         ephemeral_pubkey: PublicKey,
366         rho: [u8; 32],
367         mu: [u8; 32],
368 }
369
370 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
371 pub struct ChannelDetails {
372         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
373         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
374         /// Note that this means this value is *not* persistent - it can change once during the
375         /// lifetime of the channel.
376         pub channel_id: [u8; 32],
377         /// The position of the funding transaction in the chain. None if the funding transaction has
378         /// not yet been confirmed and the channel fully opened.
379         pub short_channel_id: Option<u64>,
380         /// The node_id of our counterparty
381         pub remote_network_id: PublicKey,
382         /// The value, in satoshis, of this channel as appears in the funding output
383         pub channel_value_satoshis: u64,
384         /// The user_id passed in to create_channel, or 0 if the channel was inbound.
385         pub user_id: u64,
386 }
387
388 macro_rules! handle_error {
389         ($self: ident, $internal: expr, $their_node_id: expr) => {
390                 match $internal {
391                         Ok(msg) => Ok(msg),
392                         Err(MsgHandleErrInternal { err, shutdown_finish }) => {
393                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
394                                         $self.finish_force_close_channel(shutdown_res);
395                                         if let Some(update) = update_option {
396                                                 let mut channel_state = $self.channel_state.lock().unwrap();
397                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
398                                                         msg: update
399                                                 });
400                                         }
401                                 }
402                                 Err(err)
403                         },
404                 }
405         }
406 }
407
408 macro_rules! break_chan_entry {
409         ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
410                 match $res {
411                         Ok(res) => res,
412                         Err(ChannelError::Ignore(msg)) => {
413                                 break Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
414                         },
415                         Err(ChannelError::Close(msg)) => {
416                                 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
417                                 let (channel_id, mut chan) = $entry.remove_entry();
418                                 if let Some(short_id) = chan.get_short_channel_id() {
419                                         $channel_state.short_to_id.remove(&short_id);
420                                 }
421                                 break Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
422                         },
423                 }
424         }
425 }
426
427 macro_rules! try_chan_entry {
428         ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
429                 match $res {
430                         Ok(res) => res,
431                         Err(ChannelError::Ignore(msg)) => {
432                                 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
433                         },
434                         Err(ChannelError::Close(msg)) => {
435                                 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
436                                 let (channel_id, mut chan) = $entry.remove_entry();
437                                 if let Some(short_id) = chan.get_short_channel_id() {
438                                         $channel_state.short_to_id.remove(&short_id);
439                                 }
440                                 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
441                         },
442                 }
443         }
444 }
445
446 macro_rules! return_monitor_err {
447         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
448                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new())
449         };
450         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $raa_first_dropped_cs: expr) => {
451                 if $action_type != RAACommitmentOrder::RevokeAndACKFirst { panic!("Bad return_monitor_err call!"); }
452                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new(), $raa_first_dropped_cs)
453         };
454         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr) => {
455                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, $failed_forwards, $failed_fails, false)
456         };
457         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr, $raa_first_dropped_cs: expr) => {
458                 match $err {
459                         ChannelMonitorUpdateErr::PermanentFailure => {
460                                 let (channel_id, mut chan) = $entry.remove_entry();
461                                 if let Some(short_id) = chan.get_short_channel_id() {
462                                         $channel_state.short_to_id.remove(&short_id);
463                                 }
464                                 // TODO: $failed_fails is dropped here, which will cause other channels to hit the
465                                 // chain in a confused state! We need to move them into the ChannelMonitor which
466                                 // will be responsible for failing backwards once things confirm on-chain.
467                                 // It's ok that we drop $failed_forwards here - at this point we'd rather they
468                                 // broadcast HTLC-Timeout and pay the associated fees to get their funds back than
469                                 // us bother trying to claim it just to forward on to another peer. If we're
470                                 // splitting hairs we'd prefer to claim payments that were to us, but we haven't
471                                 // given up the preimage yet, so might as well just wait until the payment is
472                                 // retried, avoiding the on-chain fees.
473                                 return Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
474                         },
475                         ChannelMonitorUpdateErr::TemporaryFailure => {
476                                 $entry.get_mut().monitor_update_failed($action_type, $failed_forwards, $failed_fails, $raa_first_dropped_cs);
477                                 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore("Failed to update ChannelMonitor"), *$entry.key()));
478                         },
479                 }
480         }
481 }
482
483 // Does not break in case of TemporaryFailure!
484 macro_rules! maybe_break_monitor_err {
485         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
486                 match $err {
487                         ChannelMonitorUpdateErr::PermanentFailure => {
488                                 let (channel_id, mut chan) = $entry.remove_entry();
489                                 if let Some(short_id) = chan.get_short_channel_id() {
490                                         $channel_state.short_to_id.remove(&short_id);
491                                 }
492                                 break Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
493                         },
494                         ChannelMonitorUpdateErr::TemporaryFailure => {
495                                 $entry.get_mut().monitor_update_failed($action_type, Vec::new(), Vec::new(), false);
496                         },
497                 }
498         }
499 }
500
501 impl ChannelManager {
502         /// Constructs a new ChannelManager to hold several channels and route between them.
503         ///
504         /// This is the main "logic hub" for all channel-related actions, and implements
505         /// ChannelMessageHandler.
506         ///
507         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
508         ///
509         /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
510         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> {
511                 let secp_ctx = Secp256k1::new();
512
513                 let res = Arc::new(ChannelManager {
514                         default_configuration: config.clone(),
515                         genesis_hash: genesis_block(network).header.bitcoin_hash(),
516                         fee_estimator: feeest.clone(),
517                         monitor: monitor.clone(),
518                         chain_monitor,
519                         tx_broadcaster,
520
521                         latest_block_height: AtomicUsize::new(0), //TODO: Get an init value
522                         last_block_hash: Mutex::new(Default::default()),
523                         secp_ctx,
524
525                         channel_state: Mutex::new(ChannelHolder{
526                                 by_id: HashMap::new(),
527                                 short_to_id: HashMap::new(),
528                                 next_forward: Instant::now(),
529                                 forward_htlcs: HashMap::new(),
530                                 claimable_htlcs: HashMap::new(),
531                                 pending_msg_events: Vec::new(),
532                         }),
533                         our_network_key: keys_manager.get_node_secret(),
534
535                         pending_events: Mutex::new(Vec::new()),
536                         total_consistency_lock: RwLock::new(()),
537
538                         keys_manager,
539
540                         logger,
541                 });
542                 let weak_res = Arc::downgrade(&res);
543                 res.chain_monitor.register_listener(weak_res);
544                 Ok(res)
545         }
546
547         /// Creates a new outbound channel to the given remote node and with the given value.
548         ///
549         /// user_id will be provided back as user_channel_id in FundingGenerationReady and
550         /// FundingBroadcastSafe events to allow tracking of which events correspond with which
551         /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
552         /// may wish to avoid using 0 for user_id here.
553         ///
554         /// If successful, will generate a SendOpenChannel message event, so you should probably poll
555         /// PeerManager::process_events afterwards.
556         ///
557         /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
558         /// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
559         pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64) -> Result<(), APIError> {
560                 if channel_value_satoshis < 1000 {
561                         return Err(APIError::APIMisuseError { err: "channel_value must be at least 1000 satoshis" });
562                 }
563
564                 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)?;
565                 let res = channel.get_open_channel(self.genesis_hash.clone(), &*self.fee_estimator);
566
567                 let _ = self.total_consistency_lock.read().unwrap();
568                 let mut channel_state = self.channel_state.lock().unwrap();
569                 match channel_state.by_id.entry(channel.channel_id()) {
570                         hash_map::Entry::Occupied(_) => {
571                                 if cfg!(feature = "fuzztarget") {
572                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG" });
573                                 } else {
574                                         panic!("RNG is bad???");
575                                 }
576                         },
577                         hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
578                 }
579                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
580                         node_id: their_network_key,
581                         msg: res,
582                 });
583                 Ok(())
584         }
585
586         /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
587         /// more information.
588         pub fn list_channels(&self) -> Vec<ChannelDetails> {
589                 let channel_state = self.channel_state.lock().unwrap();
590                 let mut res = Vec::with_capacity(channel_state.by_id.len());
591                 for (channel_id, channel) in channel_state.by_id.iter() {
592                         res.push(ChannelDetails {
593                                 channel_id: (*channel_id).clone(),
594                                 short_channel_id: channel.get_short_channel_id(),
595                                 remote_network_id: channel.get_their_node_id(),
596                                 channel_value_satoshis: channel.get_value_satoshis(),
597                                 user_id: channel.get_user_id(),
598                         });
599                 }
600                 res
601         }
602
603         /// Gets the list of usable channels, in random order. Useful as an argument to
604         /// Router::get_route to ensure non-announced channels are used.
605         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
606                 let channel_state = self.channel_state.lock().unwrap();
607                 let mut res = Vec::with_capacity(channel_state.by_id.len());
608                 for (channel_id, channel) in channel_state.by_id.iter() {
609                         // Note we use is_live here instead of usable which leads to somewhat confused
610                         // internal/external nomenclature, but that's ok cause that's probably what the user
611                         // really wanted anyway.
612                         if channel.is_live() {
613                                 res.push(ChannelDetails {
614                                         channel_id: (*channel_id).clone(),
615                                         short_channel_id: channel.get_short_channel_id(),
616                                         remote_network_id: channel.get_their_node_id(),
617                                         channel_value_satoshis: channel.get_value_satoshis(),
618                                         user_id: channel.get_user_id(),
619                                 });
620                         }
621                 }
622                 res
623         }
624
625         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
626         /// will be accepted on the given channel, and after additional timeout/the closing of all
627         /// pending HTLCs, the channel will be closed on chain.
628         ///
629         /// May generate a SendShutdown message event on success, which should be relayed.
630         pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
631                 let _ = self.total_consistency_lock.read().unwrap();
632
633                 let (mut failed_htlcs, chan_option) = {
634                         let mut channel_state_lock = self.channel_state.lock().unwrap();
635                         let channel_state = channel_state_lock.borrow_parts();
636                         match channel_state.by_id.entry(channel_id.clone()) {
637                                 hash_map::Entry::Occupied(mut chan_entry) => {
638                                         let (shutdown_msg, failed_htlcs) = chan_entry.get_mut().get_shutdown()?;
639                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
640                                                 node_id: chan_entry.get().get_their_node_id(),
641                                                 msg: shutdown_msg
642                                         });
643                                         if chan_entry.get().is_shutdown() {
644                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
645                                                         channel_state.short_to_id.remove(&short_id);
646                                                 }
647                                                 (failed_htlcs, Some(chan_entry.remove_entry().1))
648                                         } else { (failed_htlcs, None) }
649                                 },
650                                 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: "No such channel"})
651                         }
652                 };
653                 for htlc_source in failed_htlcs.drain(..) {
654                         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() });
655                 }
656                 let chan_update = if let Some(chan) = chan_option {
657                         if let Ok(update) = self.get_channel_update(&chan) {
658                                 Some(update)
659                         } else { None }
660                 } else { None };
661
662                 if let Some(update) = chan_update {
663                         let mut channel_state = self.channel_state.lock().unwrap();
664                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
665                                 msg: update
666                         });
667                 }
668
669                 Ok(())
670         }
671
672         #[inline]
673         fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
674                 let (local_txn, mut failed_htlcs) = shutdown_res;
675                 log_trace!(self, "Finishing force-closure of channel with {} transactions to broadcast and {} HTLCs to fail", local_txn.len(), failed_htlcs.len());
676                 for htlc_source in failed_htlcs.drain(..) {
677                         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() });
678                 }
679                 for tx in local_txn {
680                         self.tx_broadcaster.broadcast_transaction(&tx);
681                 }
682         }
683
684         /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
685         /// the chain and rejecting new HTLCs on the given channel.
686         pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
687                 let _ = self.total_consistency_lock.read().unwrap();
688
689                 let mut chan = {
690                         let mut channel_state_lock = self.channel_state.lock().unwrap();
691                         let channel_state = channel_state_lock.borrow_parts();
692                         if let Some(chan) = channel_state.by_id.remove(channel_id) {
693                                 if let Some(short_id) = chan.get_short_channel_id() {
694                                         channel_state.short_to_id.remove(&short_id);
695                                 }
696                                 chan
697                         } else {
698                                 return;
699                         }
700                 };
701                 log_trace!(self, "Force-closing channel {}", log_bytes!(channel_id[..]));
702                 self.finish_force_close_channel(chan.force_shutdown());
703                 if let Ok(update) = self.get_channel_update(&chan) {
704                         let mut channel_state = self.channel_state.lock().unwrap();
705                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
706                                 msg: update
707                         });
708                 }
709         }
710
711         /// Force close all channels, immediately broadcasting the latest local commitment transaction
712         /// for each to the chain and rejecting new HTLCs on each.
713         pub fn force_close_all_channels(&self) {
714                 for chan in self.list_channels() {
715                         self.force_close_channel(&chan.channel_id);
716                 }
717         }
718
719         #[inline]
720         fn gen_rho_mu_from_shared_secret(shared_secret: &[u8]) -> ([u8; 32], [u8; 32]) {
721                 assert_eq!(shared_secret.len(), 32);
722                 ({
723                         let mut hmac = HmacEngine::<Sha256>::new(&[0x72, 0x68, 0x6f]); // rho
724                         hmac.input(&shared_secret[..]);
725                         Hmac::from_engine(hmac).into_inner()
726                 },
727                 {
728                         let mut hmac = HmacEngine::<Sha256>::new(&[0x6d, 0x75]); // mu
729                         hmac.input(&shared_secret[..]);
730                         Hmac::from_engine(hmac).into_inner()
731                 })
732         }
733
734         #[inline]
735         fn gen_um_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
736                 assert_eq!(shared_secret.len(), 32);
737                 let mut hmac = HmacEngine::<Sha256>::new(&[0x75, 0x6d]); // um
738                 hmac.input(&shared_secret[..]);
739                 Hmac::from_engine(hmac).into_inner()
740         }
741
742         #[inline]
743         fn gen_ammag_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
744                 assert_eq!(shared_secret.len(), 32);
745                 let mut hmac = HmacEngine::<Sha256>::new(&[0x61, 0x6d, 0x6d, 0x61, 0x67]); // ammag
746                 hmac.input(&shared_secret[..]);
747                 Hmac::from_engine(hmac).into_inner()
748         }
749
750         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
751         #[inline]
752         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> {
753                 let mut blinded_priv = session_priv.clone();
754                 let mut blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
755
756                 for hop in route.hops.iter() {
757                         let shared_secret = SharedSecret::new(secp_ctx, &hop.pubkey, &blinded_priv);
758
759                         let mut sha = Sha256::engine();
760                         sha.input(&blinded_pub.serialize()[..]);
761                         sha.input(&shared_secret[..]);
762                         let blinding_factor = Sha256::from_engine(sha).into_inner();
763
764                         let ephemeral_pubkey = blinded_pub;
765
766                         blinded_priv.mul_assign(secp_ctx, &SecretKey::from_slice(secp_ctx, &blinding_factor)?)?;
767                         blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
768
769                         callback(shared_secret, blinding_factor, ephemeral_pubkey, hop);
770                 }
771
772                 Ok(())
773         }
774
775         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
776         fn construct_onion_keys<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey) -> Result<Vec<OnionKeys>, secp256k1::Error> {
777                 let mut res = Vec::with_capacity(route.hops.len());
778
779                 Self::construct_onion_keys_callback(secp_ctx, route, session_priv, |shared_secret, _blinding_factor, ephemeral_pubkey, _| {
780                         let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret[..]);
781
782                         res.push(OnionKeys {
783                                 #[cfg(test)]
784                                 shared_secret,
785                                 #[cfg(test)]
786                                 blinding_factor: _blinding_factor,
787                                 ephemeral_pubkey,
788                                 rho,
789                                 mu,
790                         });
791                 })?;
792
793                 Ok(res)
794         }
795
796         /// returns the hop data, as well as the first-hop value_msat and CLTV value we should send.
797         fn build_onion_payloads(route: &Route, starting_htlc_offset: u32) -> Result<(Vec<msgs::OnionHopData>, u64, u32), APIError> {
798                 let mut cur_value_msat = 0u64;
799                 let mut cur_cltv = starting_htlc_offset;
800                 let mut last_short_channel_id = 0;
801                 let mut res: Vec<msgs::OnionHopData> = Vec::with_capacity(route.hops.len());
802                 internal_traits::test_no_dealloc::<msgs::OnionHopData>(None);
803                 unsafe { res.set_len(route.hops.len()); }
804
805                 for (idx, hop) in route.hops.iter().enumerate().rev() {
806                         // First hop gets special values so that it can check, on receipt, that everything is
807                         // exactly as it should be (and the next hop isn't trying to probe to find out if we're
808                         // the intended recipient).
809                         let value_msat = if cur_value_msat == 0 { hop.fee_msat } else { cur_value_msat };
810                         let cltv = if cur_cltv == starting_htlc_offset { hop.cltv_expiry_delta + starting_htlc_offset } else { cur_cltv };
811                         res[idx] = msgs::OnionHopData {
812                                 realm: 0,
813                                 data: msgs::OnionRealm0HopData {
814                                         short_channel_id: last_short_channel_id,
815                                         amt_to_forward: value_msat,
816                                         outgoing_cltv_value: cltv,
817                                 },
818                                 hmac: [0; 32],
819                         };
820                         cur_value_msat += hop.fee_msat;
821                         if cur_value_msat >= 21000000 * 100000000 * 1000 {
822                                 return Err(APIError::RouteError{err: "Channel fees overflowed?!"});
823                         }
824                         cur_cltv += hop.cltv_expiry_delta as u32;
825                         if cur_cltv >= 500000000 {
826                                 return Err(APIError::RouteError{err: "Channel CLTV overflowed?!"});
827                         }
828                         last_short_channel_id = hop.short_channel_id;
829                 }
830                 Ok((res, cur_value_msat, cur_cltv))
831         }
832
833         #[inline]
834         fn shift_arr_right(arr: &mut [u8; 20*65]) {
835                 unsafe {
836                         ptr::copy(arr[0..].as_ptr(), arr[65..].as_mut_ptr(), 19*65);
837                 }
838                 for i in 0..65 {
839                         arr[i] = 0;
840                 }
841         }
842
843         #[inline]
844         fn xor_bufs(dst: &mut[u8], src: &[u8]) {
845                 assert_eq!(dst.len(), src.len());
846
847                 for i in 0..dst.len() {
848                         dst[i] ^= src[i];
849                 }
850         }
851
852         const ZERO:[u8; 21*65] = [0; 21*65];
853         fn construct_onion_packet(mut payloads: Vec<msgs::OnionHopData>, onion_keys: Vec<OnionKeys>, associated_data: &PaymentHash) -> msgs::OnionPacket {
854                 let mut buf = Vec::with_capacity(21*65);
855                 buf.resize(21*65, 0);
856
857                 let filler = {
858                         let iters = payloads.len() - 1;
859                         let end_len = iters * 65;
860                         let mut res = Vec::with_capacity(end_len);
861                         res.resize(end_len, 0);
862
863                         for (i, keys) in onion_keys.iter().enumerate() {
864                                 if i == payloads.len() - 1 { continue; }
865                                 let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
866                                 chacha.process(&ChannelManager::ZERO, &mut buf); // We don't have a seek function :(
867                                 ChannelManager::xor_bufs(&mut res[0..(i + 1)*65], &buf[(20 - i)*65..21*65]);
868                         }
869                         res
870                 };
871
872                 let mut packet_data = [0; 20*65];
873                 let mut hmac_res = [0; 32];
874
875                 for (i, (payload, keys)) in payloads.iter_mut().zip(onion_keys.iter()).rev().enumerate() {
876                         ChannelManager::shift_arr_right(&mut packet_data);
877                         payload.hmac = hmac_res;
878                         packet_data[0..65].copy_from_slice(&payload.encode()[..]);
879
880                         let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
881                         chacha.process(&packet_data, &mut buf[0..20*65]);
882                         packet_data[..].copy_from_slice(&buf[0..20*65]);
883
884                         if i == 0 {
885                                 packet_data[20*65 - filler.len()..20*65].copy_from_slice(&filler[..]);
886                         }
887
888                         let mut hmac = HmacEngine::<Sha256>::new(&keys.mu);
889                         hmac.input(&packet_data);
890                         hmac.input(&associated_data.0[..]);
891                         hmac_res = Hmac::from_engine(hmac).into_inner();
892                 }
893
894                 msgs::OnionPacket{
895                         version: 0,
896                         public_key: Ok(onion_keys.first().unwrap().ephemeral_pubkey),
897                         hop_data: packet_data,
898                         hmac: hmac_res,
899                 }
900         }
901
902         /// Encrypts a failure packet. raw_packet can either be a
903         /// msgs::DecodedOnionErrorPacket.encode() result or a msgs::OnionErrorPacket.data element.
904         fn encrypt_failure_packet(shared_secret: &[u8], raw_packet: &[u8]) -> msgs::OnionErrorPacket {
905                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
906
907                 let mut packet_crypted = Vec::with_capacity(raw_packet.len());
908                 packet_crypted.resize(raw_packet.len(), 0);
909                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
910                 chacha.process(&raw_packet, &mut packet_crypted[..]);
911                 msgs::OnionErrorPacket {
912                         data: packet_crypted,
913                 }
914         }
915
916         fn build_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::DecodedOnionErrorPacket {
917                 assert_eq!(shared_secret.len(), 32);
918                 assert!(failure_data.len() <= 256 - 2);
919
920                 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
921
922                 let failuremsg = {
923                         let mut res = Vec::with_capacity(2 + failure_data.len());
924                         res.push(((failure_type >> 8) & 0xff) as u8);
925                         res.push(((failure_type >> 0) & 0xff) as u8);
926                         res.extend_from_slice(&failure_data[..]);
927                         res
928                 };
929                 let pad = {
930                         let mut res = Vec::with_capacity(256 - 2 - failure_data.len());
931                         res.resize(256 - 2 - failure_data.len(), 0);
932                         res
933                 };
934                 let mut packet = msgs::DecodedOnionErrorPacket {
935                         hmac: [0; 32],
936                         failuremsg: failuremsg,
937                         pad: pad,
938                 };
939
940                 let mut hmac = HmacEngine::<Sha256>::new(&um);
941                 hmac.input(&packet.encode()[32..]);
942                 packet.hmac = Hmac::from_engine(hmac).into_inner();
943
944                 packet
945         }
946
947         #[inline]
948         fn build_first_hop_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::OnionErrorPacket {
949                 let failure_packet = ChannelManager::build_failure_packet(shared_secret, failure_type, failure_data);
950                 ChannelManager::encrypt_failure_packet(shared_secret, &failure_packet.encode()[..])
951         }
952
953         fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder>) {
954                 macro_rules! return_malformed_err {
955                         ($msg: expr, $err_code: expr) => {
956                                 {
957                                         log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
958                                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
959                                                 channel_id: msg.channel_id,
960                                                 htlc_id: msg.htlc_id,
961                                                 sha256_of_onion: Sha256::hash(&msg.onion_routing_packet.hop_data).into_inner(),
962                                                 failure_code: $err_code,
963                                         })), self.channel_state.lock().unwrap());
964                                 }
965                         }
966                 }
967
968                 if let Err(_) = msg.onion_routing_packet.public_key {
969                         return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
970                 }
971
972                 let shared_secret = {
973                         let mut arr = [0; 32];
974                         arr.copy_from_slice(&SharedSecret::new(&self.secp_ctx, &msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key)[..]);
975                         arr
976                 };
977                 let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
978
979                 if msg.onion_routing_packet.version != 0 {
980                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
981                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
982                         //the hash doesn't really serve any purpuse - in the case of hashing all data, the
983                         //receiving node would have to brute force to figure out which version was put in the
984                         //packet by the node that send us the message, in the case of hashing the hop_data, the
985                         //node knows the HMAC matched, so they already know what is there...
986                         return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
987                 }
988
989
990                 let mut hmac = HmacEngine::<Sha256>::new(&mu);
991                 hmac.input(&msg.onion_routing_packet.hop_data);
992                 hmac.input(&msg.payment_hash.0[..]);
993                 if !fixed_time_eq(&Hmac::from_engine(hmac).into_inner(), &msg.onion_routing_packet.hmac) {
994                         return_malformed_err!("HMAC Check failed", 0x8000 | 0x4000 | 5);
995                 }
996
997                 let mut channel_state = None;
998                 macro_rules! return_err {
999                         ($msg: expr, $err_code: expr, $data: expr) => {
1000                                 {
1001                                         log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
1002                                         if channel_state.is_none() {
1003                                                 channel_state = Some(self.channel_state.lock().unwrap());
1004                                         }
1005                                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
1006                                                 channel_id: msg.channel_id,
1007                                                 htlc_id: msg.htlc_id,
1008                                                 reason: ChannelManager::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
1009                                         })), channel_state.unwrap());
1010                                 }
1011                         }
1012                 }
1013
1014                 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
1015                 let next_hop_data = {
1016                         let mut decoded = [0; 65];
1017                         chacha.process(&msg.onion_routing_packet.hop_data[0..65], &mut decoded);
1018                         match msgs::OnionHopData::read(&mut Cursor::new(&decoded[..])) {
1019                                 Err(err) => {
1020                                         let error_code = match err {
1021                                                 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
1022                                                 _ => 0x2000 | 2, // Should never happen
1023                                         };
1024                                         return_err!("Unable to decode our hop data", error_code, &[0;0]);
1025                                 },
1026                                 Ok(msg) => msg
1027                         }
1028                 };
1029
1030                 let pending_forward_info = if next_hop_data.hmac == [0; 32] {
1031                                 // OUR PAYMENT!
1032                                 // final_expiry_too_soon
1033                                 if (msg.cltv_expiry as u64) < self.latest_block_height.load(Ordering::Acquire) as u64 + (CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS) as u64 {
1034                                         return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
1035                                 }
1036                                 // final_incorrect_htlc_amount
1037                                 if next_hop_data.data.amt_to_forward > msg.amount_msat {
1038                                         return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
1039                                 }
1040                                 // final_incorrect_cltv_expiry
1041                                 if next_hop_data.data.outgoing_cltv_value != msg.cltv_expiry {
1042                                         return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
1043                                 }
1044
1045                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
1046                                 // message, however that would leak that we are the recipient of this payment, so
1047                                 // instead we stay symmetric with the forwarding case, only responding (after a
1048                                 // delay) once they've send us a commitment_signed!
1049
1050                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1051                                         onion_packet: None,
1052                                         payment_hash: msg.payment_hash.clone(),
1053                                         short_channel_id: 0,
1054                                         incoming_shared_secret: shared_secret,
1055                                         amt_to_forward: next_hop_data.data.amt_to_forward,
1056                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1057                                 })
1058                         } else {
1059                                 let mut new_packet_data = [0; 20*65];
1060                                 chacha.process(&msg.onion_routing_packet.hop_data[65..], &mut new_packet_data[0..19*65]);
1061                                 chacha.process(&ChannelManager::ZERO[0..65], &mut new_packet_data[19*65..]);
1062
1063                                 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
1064
1065                                 let blinding_factor = {
1066                                         let mut sha = Sha256::engine();
1067                                         sha.input(&new_pubkey.serialize()[..]);
1068                                         sha.input(&shared_secret);
1069                                         SecretKey::from_slice(&self.secp_ctx, &Sha256::from_engine(sha).into_inner()).expect("SHA-256 is broken?")
1070                                 };
1071
1072                                 let public_key = if let Err(e) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor) {
1073                                         Err(e)
1074                                 } else { Ok(new_pubkey) };
1075
1076                                 let outgoing_packet = msgs::OnionPacket {
1077                                         version: 0,
1078                                         public_key,
1079                                         hop_data: new_packet_data,
1080                                         hmac: next_hop_data.hmac.clone(),
1081                                 };
1082
1083                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1084                                         onion_packet: Some(outgoing_packet),
1085                                         payment_hash: msg.payment_hash.clone(),
1086                                         short_channel_id: next_hop_data.data.short_channel_id,
1087                                         incoming_shared_secret: shared_secret,
1088                                         amt_to_forward: next_hop_data.data.amt_to_forward,
1089                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1090                                 })
1091                         };
1092
1093                 channel_state = Some(self.channel_state.lock().unwrap());
1094                 if let &PendingHTLCStatus::Forward(PendingForwardHTLCInfo { ref onion_packet, ref short_channel_id, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
1095                         if onion_packet.is_some() { // If short_channel_id is 0 here, we'll reject them in the body here
1096                                 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
1097                                 let forwarding_id = match id_option {
1098                                         None => { // unknown_next_peer
1099                                                 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
1100                                         },
1101                                         Some(id) => id.clone(),
1102                                 };
1103                                 if let Some((err, code, chan_update)) = loop {
1104                                         let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
1105
1106                                         // Note that we could technically not return an error yet here and just hope
1107                                         // that the connection is reestablished or monitor updated by the time we get
1108                                         // around to doing the actual forward, but better to fail early if we can and
1109                                         // hopefully an attacker trying to path-trace payments cannot make this occur
1110                                         // on a small/per-node/per-channel scale.
1111                                         if !chan.is_live() { // channel_disabled
1112                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
1113                                         }
1114                                         if *amt_to_forward < chan.get_their_htlc_minimum_msat() { // amount_below_minimum
1115                                                 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
1116                                         }
1117                                         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) });
1118                                         if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
1119                                                 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())));
1120                                         }
1121                                         if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 { // incorrect_cltv_expiry
1122                                                 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())));
1123                                         }
1124                                         let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1125                                         // We want to have at least HTLC_FAIL_TIMEOUT_BLOCKS to fail prior to going on chain CLAIM_BUFFER blocks before expiration
1126                                         if msg.cltv_expiry <= cur_height + CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS as u32 { // expiry_too_soon
1127                                                 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1128                                         }
1129                                         if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
1130                                                 break Some(("CLTV expiry is too far in the future", 21, None));
1131                                         }
1132                                         break None;
1133                                 }
1134                                 {
1135                                         let mut res = Vec::with_capacity(8 + 128);
1136                                         if let Some(chan_update) = chan_update {
1137                                                 if code == 0x1000 | 11 || code == 0x1000 | 12 {
1138                                                         res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
1139                                                 }
1140                                                 else if code == 0x1000 | 13 {
1141                                                         res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
1142                                                 }
1143                                                 else if code == 0x1000 | 20 {
1144                                                         res.extend_from_slice(&byte_utils::be16_to_array(chan_update.contents.flags));
1145                                                 }
1146                                                 res.extend_from_slice(&chan_update.encode_with_len()[..]);
1147                                         }
1148                                         return_err!(err, code, &res[..]);
1149                                 }
1150                         }
1151                 }
1152
1153                 (pending_forward_info, channel_state.unwrap())
1154         }
1155
1156         /// only fails if the channel does not yet have an assigned short_id
1157         /// May be called with channel_state already locked!
1158         fn get_channel_update(&self, chan: &Channel) -> Result<msgs::ChannelUpdate, HandleError> {
1159                 let short_channel_id = match chan.get_short_channel_id() {
1160                         None => return Err(HandleError{err: "Channel not yet established", action: None}),
1161                         Some(id) => id,
1162                 };
1163
1164                 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_their_node_id().serialize()[..];
1165
1166                 let unsigned = msgs::UnsignedChannelUpdate {
1167                         chain_hash: self.genesis_hash,
1168                         short_channel_id: short_channel_id,
1169                         timestamp: chan.get_channel_update_count(),
1170                         flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
1171                         cltv_expiry_delta: CLTV_EXPIRY_DELTA,
1172                         htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
1173                         fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
1174                         fee_proportional_millionths: chan.get_fee_proportional_millionths(),
1175                         excess_data: Vec::new(),
1176                 };
1177
1178                 let msg_hash = Sha256dHash::from_data(&unsigned.encode()[..]);
1179                 let sig = self.secp_ctx.sign(&Message::from_slice(&msg_hash[..]).unwrap(), &self.our_network_key);
1180
1181                 Ok(msgs::ChannelUpdate {
1182                         signature: sig,
1183                         contents: unsigned
1184                 })
1185         }
1186
1187         /// Sends a payment along a given route.
1188         ///
1189         /// Value parameters are provided via the last hop in route, see documentation for RouteHop
1190         /// fields for more info.
1191         ///
1192         /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
1193         /// payment), we don't do anything to stop you! We always try to ensure that if the provided
1194         /// next hop knows the preimage to payment_hash they can claim an additional amount as
1195         /// specified in the last hop in the route! Thus, you should probably do your own
1196         /// payment_preimage tracking (which you should already be doing as they represent "proof of
1197         /// payment") and prevent double-sends yourself.
1198         ///
1199         /// May generate a SendHTLCs message event on success, which should be relayed.
1200         ///
1201         /// Raises APIError::RoutError when invalid route or forward parameter
1202         /// (cltv_delta, fee, node public key) is specified.
1203         /// Raises APIError::ChannelUnavailable if the next-hop channel is not available for updates
1204         /// (including due to previous monitor update failure or new permanent monitor update failure).
1205         /// Raised APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
1206         /// relevant updates.
1207         ///
1208         /// In case of APIError::RouteError/APIError::ChannelUnavailable, the payment send has failed
1209         /// and you may wish to retry via a different route immediately.
1210         /// In case of APIError::MonitorUpdateFailed, the commitment update has been irrevocably
1211         /// committed on our end and we're just waiting for a monitor update to send it. Do NOT retry
1212         /// the payment via a different route unless you intend to pay twice!
1213         pub fn send_payment(&self, route: Route, payment_hash: PaymentHash) -> Result<(), APIError> {
1214                 if route.hops.len() < 1 || route.hops.len() > 20 {
1215                         return Err(APIError::RouteError{err: "Route didn't go anywhere/had bogus size"});
1216                 }
1217                 let our_node_id = self.get_our_node_id();
1218                 for (idx, hop) in route.hops.iter().enumerate() {
1219                         if idx != route.hops.len() - 1 && hop.pubkey == our_node_id {
1220                                 return Err(APIError::RouteError{err: "Route went through us but wasn't a simple rebalance loop to us"});
1221                         }
1222                 }
1223
1224                 let session_priv = self.keys_manager.get_session_key();
1225
1226                 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1227
1228                 let onion_keys = secp_call!(ChannelManager::construct_onion_keys(&self.secp_ctx, &route, &session_priv),
1229                                 APIError::RouteError{err: "Pubkey along hop was maliciously selected"});
1230                 let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height)?;
1231                 let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
1232
1233                 let _ = self.total_consistency_lock.read().unwrap();
1234
1235                 let err: Result<(), _> = loop {
1236                         let mut channel_lock = self.channel_state.lock().unwrap();
1237
1238                         let id = match channel_lock.short_to_id.get(&route.hops.first().unwrap().short_channel_id) {
1239                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!"}),
1240                                 Some(id) => id.clone(),
1241                         };
1242
1243                         let channel_state = channel_lock.borrow_parts();
1244                         if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) {
1245                                 match {
1246                                         if chan.get().get_their_node_id() != route.hops.first().unwrap().pubkey {
1247                                                 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1248                                         }
1249                                         if !chan.get().is_live() {
1250                                                 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!"});
1251                                         }
1252                                         break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1253                                                 route: route.clone(),
1254                                                 session_priv: session_priv.clone(),
1255                                                 first_hop_htlc_msat: htlc_msat,
1256                                         }, onion_packet), channel_state, chan)
1257                                 } {
1258                                         Some((update_add, commitment_signed, chan_monitor)) => {
1259                                                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1260                                                         maybe_break_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst);
1261                                                         // Note that MonitorUpdateFailed here indicates (per function docs)
1262                                                         // that we will resent the commitment update once we unfree monitor
1263                                                         // updating, so we have to take special care that we don't return
1264                                                         // something else in case we will resend later!
1265                                                         return Err(APIError::MonitorUpdateFailed);
1266                                                 }
1267
1268                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1269                                                         node_id: route.hops.first().unwrap().pubkey,
1270                                                         updates: msgs::CommitmentUpdate {
1271                                                                 update_add_htlcs: vec![update_add],
1272                                                                 update_fulfill_htlcs: Vec::new(),
1273                                                                 update_fail_htlcs: Vec::new(),
1274                                                                 update_fail_malformed_htlcs: Vec::new(),
1275                                                                 update_fee: None,
1276                                                                 commitment_signed,
1277                                                         },
1278                                                 });
1279                                         },
1280                                         None => {},
1281                                 }
1282                         } else { unreachable!(); }
1283                         return Ok(());
1284                 };
1285
1286                 match handle_error!(self, err, route.hops.first().unwrap().pubkey) {
1287                         Ok(_) => unreachable!(),
1288                         Err(e) => {
1289                                 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
1290                                 } else {
1291                                         log_error!(self, "Got bad keys: {}!", e.err);
1292                                         let mut channel_state = self.channel_state.lock().unwrap();
1293                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1294                                                 node_id: route.hops.first().unwrap().pubkey,
1295                                                 action: e.action,
1296                                         });
1297                                 }
1298                                 Err(APIError::ChannelUnavailable { err: e.err })
1299                         },
1300                 }
1301         }
1302
1303         /// Call this upon creation of a funding transaction for the given channel.
1304         ///
1305         /// Note that ALL inputs in the transaction pointed to by funding_txo MUST spend SegWit outputs
1306         /// or your counterparty can steal your funds!
1307         ///
1308         /// Panics if a funding transaction has already been provided for this channel.
1309         ///
1310         /// May panic if the funding_txo is duplicative with some other channel (note that this should
1311         /// be trivially prevented by using unique funding transaction keys per-channel).
1312         pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1313                 let _ = self.total_consistency_lock.read().unwrap();
1314
1315                 let (chan, msg, chan_monitor) = {
1316                         let (res, chan) = {
1317                                 let mut channel_state = self.channel_state.lock().unwrap();
1318                                 match channel_state.by_id.remove(temporary_channel_id) {
1319                                         Some(mut chan) => {
1320                                                 (chan.get_outbound_funding_created(funding_txo)
1321                                                         .map_err(|e| if let ChannelError::Close(msg) = e {
1322                                                                 MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.force_shutdown(), None)
1323                                                         } else { unreachable!(); })
1324                                                 , chan)
1325                                         },
1326                                         None => return
1327                                 }
1328                         };
1329                         match handle_error!(self, res, chan.get_their_node_id()) {
1330                                 Ok(funding_msg) => {
1331                                         (chan, funding_msg.0, funding_msg.1)
1332                                 },
1333                                 Err(e) => {
1334                                         log_error!(self, "Got bad signatures: {}!", e.err);
1335                                         let mut channel_state = self.channel_state.lock().unwrap();
1336                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1337                                                 node_id: chan.get_their_node_id(),
1338                                                 action: e.action,
1339                                         });
1340                                         return;
1341                                 },
1342                         }
1343                 };
1344                 // Because we have exclusive ownership of the channel here we can release the channel_state
1345                 // lock before add_update_monitor
1346                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1347                         unimplemented!();
1348                 }
1349
1350                 let mut channel_state = self.channel_state.lock().unwrap();
1351                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
1352                         node_id: chan.get_their_node_id(),
1353                         msg: msg,
1354                 });
1355                 match channel_state.by_id.entry(chan.channel_id()) {
1356                         hash_map::Entry::Occupied(_) => {
1357                                 panic!("Generated duplicate funding txid?");
1358                         },
1359                         hash_map::Entry::Vacant(e) => {
1360                                 e.insert(chan);
1361                         }
1362                 }
1363         }
1364
1365         fn get_announcement_sigs(&self, chan: &Channel) -> Option<msgs::AnnouncementSignatures> {
1366                 if !chan.should_announce() { return None }
1367
1368                 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1369                         Ok(res) => res,
1370                         Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1371                 };
1372                 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
1373                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1374
1375                 Some(msgs::AnnouncementSignatures {
1376                         channel_id: chan.channel_id(),
1377                         short_channel_id: chan.get_short_channel_id().unwrap(),
1378                         node_signature: our_node_sig,
1379                         bitcoin_signature: our_bitcoin_sig,
1380                 })
1381         }
1382
1383         /// Processes HTLCs which are pending waiting on random forward delay.
1384         ///
1385         /// Should only really ever be called in response to an PendingHTLCsForwardable event.
1386         /// Will likely generate further events.
1387         pub fn process_pending_htlc_forwards(&self) {
1388                 let _ = self.total_consistency_lock.read().unwrap();
1389
1390                 let mut new_events = Vec::new();
1391                 let mut failed_forwards = Vec::new();
1392                 {
1393                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1394                         let channel_state = channel_state_lock.borrow_parts();
1395
1396                         if cfg!(not(feature = "fuzztarget")) && Instant::now() < *channel_state.next_forward {
1397                                 return;
1398                         }
1399
1400                         for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1401                                 if short_chan_id != 0 {
1402                                         let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1403                                                 Some(chan_id) => chan_id.clone(),
1404                                                 None => {
1405                                                         failed_forwards.reserve(pending_forwards.len());
1406                                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1407                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1408                                                                         short_channel_id: prev_short_channel_id,
1409                                                                         htlc_id: prev_htlc_id,
1410                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1411                                                                 });
1412                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
1413                                                         }
1414                                                         continue;
1415                                                 }
1416                                         };
1417                                         let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();
1418
1419                                         let mut add_htlc_msgs = Vec::new();
1420                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1421                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1422                                                         short_channel_id: prev_short_channel_id,
1423                                                         htlc_id: prev_htlc_id,
1424                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1425                                                 });
1426                                                 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()) {
1427                                                         Err(_e) => {
1428                                                                 let chan_update = self.get_channel_update(forward_chan).unwrap();
1429                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x1000 | 7, Some(chan_update)));
1430                                                                 continue;
1431                                                         },
1432                                                         Ok(update_add) => {
1433                                                                 match update_add {
1434                                                                         Some(msg) => { add_htlc_msgs.push(msg); },
1435                                                                         None => {
1436                                                                                 // Nothing to do here...we're waiting on a remote
1437                                                                                 // revoke_and_ack before we can add anymore HTLCs. The Channel
1438                                                                                 // will automatically handle building the update_add_htlc and
1439                                                                                 // commitment_signed messages when we can.
1440                                                                                 // TODO: Do some kind of timer to set the channel as !is_live()
1441                                                                                 // as we don't really want others relying on us relaying through
1442                                                                                 // this channel currently :/.
1443                                                                         }
1444                                                                 }
1445                                                         }
1446                                                 }
1447                                         }
1448
1449                                         if !add_htlc_msgs.is_empty() {
1450                                                 let (commitment_msg, monitor) = match forward_chan.send_commitment() {
1451                                                         Ok(res) => res,
1452                                                         Err(e) => {
1453                                                                 if let ChannelError::Ignore(_) = e {
1454                                                                         panic!("Stated return value requirements in send_commitment() were not met");
1455                                                                 }
1456                                                                 //TODO: Handle...this is bad!
1457                                                                 continue;
1458                                                         },
1459                                                 };
1460                                                 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
1461                                                         unimplemented!();
1462                                                 }
1463                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1464                                                         node_id: forward_chan.get_their_node_id(),
1465                                                         updates: msgs::CommitmentUpdate {
1466                                                                 update_add_htlcs: add_htlc_msgs,
1467                                                                 update_fulfill_htlcs: Vec::new(),
1468                                                                 update_fail_htlcs: Vec::new(),
1469                                                                 update_fail_malformed_htlcs: Vec::new(),
1470                                                                 update_fee: None,
1471                                                                 commitment_signed: commitment_msg,
1472                                                         },
1473                                                 });
1474                                         }
1475                                 } else {
1476                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1477                                                 let prev_hop_data = HTLCPreviousHopData {
1478                                                         short_channel_id: prev_short_channel_id,
1479                                                         htlc_id: prev_htlc_id,
1480                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1481                                                 };
1482                                                 match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
1483                                                         hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(prev_hop_data),
1484                                                         hash_map::Entry::Vacant(entry) => { entry.insert(vec![prev_hop_data]); },
1485                                                 };
1486                                                 new_events.push(events::Event::PaymentReceived {
1487                                                         payment_hash: forward_info.payment_hash,
1488                                                         amt: forward_info.amt_to_forward,
1489                                                 });
1490                                         }
1491                                 }
1492                         }
1493                 }
1494
1495                 for (htlc_source, payment_hash, failure_code, update) in failed_forwards.drain(..) {
1496                         match update {
1497                                 None => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code, data: Vec::new() }),
1498                                 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() }),
1499                         };
1500                 }
1501
1502                 if new_events.is_empty() { return }
1503                 let mut events = self.pending_events.lock().unwrap();
1504                 events.append(&mut new_events);
1505         }
1506
1507         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
1508         /// after a PaymentReceived event.
1509         /// expected_value is the value you expected the payment to be for (not the amount it actually
1510         /// was for from the PaymentReceived event).
1511         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash, expected_value: u64) -> bool {
1512                 let _ = self.total_consistency_lock.read().unwrap();
1513
1514                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1515                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(payment_hash);
1516                 if let Some(mut sources) = removed_source {
1517                         for htlc_with_hash in sources.drain(..) {
1518                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1519                                 self.fail_htlc_backwards_internal(channel_state.take().unwrap(),
1520                                                 HTLCSource::PreviousHopData(htlc_with_hash), payment_hash,
1521                                                 HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: byte_utils::be64_to_array(expected_value).to_vec() });
1522                         }
1523                         true
1524                 } else { false }
1525         }
1526
1527         /// Fails an HTLC backwards to the sender of it to us.
1528         /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
1529         /// There are several callsites that do stupid things like loop over a list of payment_hashes
1530         /// to fail and take the channel_state lock for each iteration (as we take ownership and may
1531         /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
1532         /// still-available channels.
1533         fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
1534                 match source {
1535                         HTLCSource::OutboundRoute { ref route, .. } => {
1536                                 log_trace!(self, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1537                                 mem::drop(channel_state_lock);
1538                                 match &onion_error {
1539                                         &HTLCFailReason::ErrorPacket { ref err } => {
1540 #[cfg(test)]
1541                                                 let (channel_update, payment_retryable, onion_error_code) = self.process_onion_failure(&source, err.data.clone());
1542 #[cfg(not(test))]
1543                                                 let (channel_update, payment_retryable, _) = self.process_onion_failure(&source, err.data.clone());
1544                                                 // TODO: If we decided to blame ourselves (or one of our channels) in
1545                                                 // process_onion_failure we should close that channel as it implies our
1546                                                 // next-hop is needlessly blaming us!
1547                                                 if let Some(update) = channel_update {
1548                                                         self.channel_state.lock().unwrap().pending_msg_events.push(
1549                                                                 events::MessageSendEvent::PaymentFailureNetworkUpdate {
1550                                                                         update,
1551                                                                 }
1552                                                         );
1553                                                 }
1554                                                 self.pending_events.lock().unwrap().push(
1555                                                         events::Event::PaymentFailed {
1556                                                                 payment_hash: payment_hash.clone(),
1557                                                                 rejected_by_dest: !payment_retryable,
1558 #[cfg(test)]
1559                                                                 error_code: onion_error_code
1560                                                         }
1561                                                 );
1562                                         },
1563                                         &HTLCFailReason::Reason {
1564 #[cfg(test)]
1565                                                         ref failure_code,
1566                                                         .. } => {
1567                                                 // we get a fail_malformed_htlc from the first hop
1568                                                 // TODO: We'd like to generate a PaymentFailureNetworkUpdate for temporary
1569                                                 // failures here, but that would be insufficient as Router::get_route
1570                                                 // generally ignores its view of our own channels as we provide them via
1571                                                 // ChannelDetails.
1572                                                 // TODO: For non-temporary failures, we really should be closing the
1573                                                 // channel here as we apparently can't relay through them anyway.
1574                                                 self.pending_events.lock().unwrap().push(
1575                                                         events::Event::PaymentFailed {
1576                                                                 payment_hash: payment_hash.clone(),
1577                                                                 rejected_by_dest: route.hops.len() == 1,
1578 #[cfg(test)]
1579                                                                 error_code: Some(*failure_code),
1580                                                         }
1581                                                 );
1582                                         }
1583                                 }
1584                         },
1585                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
1586                                 let err_packet = match onion_error {
1587                                         HTLCFailReason::Reason { failure_code, data } => {
1588                                                 log_trace!(self, "Failing HTLC with payment_hash {} backwards from us with code {}", log_bytes!(payment_hash.0), failure_code);
1589                                                 let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1590                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1591                                         },
1592                                         HTLCFailReason::ErrorPacket { err } => {
1593                                                 log_trace!(self, "Failing HTLC with payment_hash {} backwards with pre-built ErrorPacket", log_bytes!(payment_hash.0));
1594                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1595                                         }
1596                                 };
1597
1598                                 let channel_state = channel_state_lock.borrow_parts();
1599
1600                                 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1601                                         Some(chan_id) => chan_id.clone(),
1602                                         None => return
1603                                 };
1604
1605                                 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1606                                 match chan.get_update_fail_htlc_and_commit(htlc_id, err_packet) {
1607                                         Ok(Some((msg, commitment_msg, chan_monitor))) => {
1608                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1609                                                         unimplemented!();
1610                                                 }
1611                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1612                                                         node_id: chan.get_their_node_id(),
1613                                                         updates: msgs::CommitmentUpdate {
1614                                                                 update_add_htlcs: Vec::new(),
1615                                                                 update_fulfill_htlcs: Vec::new(),
1616                                                                 update_fail_htlcs: vec![msg],
1617                                                                 update_fail_malformed_htlcs: Vec::new(),
1618                                                                 update_fee: None,
1619                                                                 commitment_signed: commitment_msg,
1620                                                         },
1621                                                 });
1622                                         },
1623                                         Ok(None) => {},
1624                                         Err(_e) => {
1625                                                 //TODO: Do something with e?
1626                                                 return;
1627                                         },
1628                                 }
1629                         },
1630                 }
1631         }
1632
1633         /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1634         /// generating message events for the net layer to claim the payment, if possible. Thus, you
1635         /// should probably kick the net layer to go send messages if this returns true!
1636         ///
1637         /// May panic if called except in response to a PaymentReceived event.
1638         pub fn claim_funds(&self, payment_preimage: PaymentPreimage) -> bool {
1639                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1640
1641                 let _ = self.total_consistency_lock.read().unwrap();
1642
1643                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1644                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&payment_hash);
1645                 if let Some(mut sources) = removed_source {
1646                         for htlc_with_hash in sources.drain(..) {
1647                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1648                                 self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_preimage);
1649                         }
1650                         true
1651                 } else { false }
1652         }
1653         fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_preimage: PaymentPreimage) {
1654                 match source {
1655                         HTLCSource::OutboundRoute { .. } => {
1656                                 mem::drop(channel_state_lock);
1657                                 let mut pending_events = self.pending_events.lock().unwrap();
1658                                 pending_events.push(events::Event::PaymentSent {
1659                                         payment_preimage
1660                                 });
1661                         },
1662                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, .. }) => {
1663                                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1664                                 let channel_state = channel_state_lock.borrow_parts();
1665
1666                                 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1667                                         Some(chan_id) => chan_id.clone(),
1668                                         None => {
1669                                                 // TODO: There is probably a channel manager somewhere that needs to
1670                                                 // learn the preimage as the channel already hit the chain and that's
1671                                                 // why its missing.
1672                                                 return
1673                                         }
1674                                 };
1675
1676                                 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1677                                 match chan.get_update_fulfill_htlc_and_commit(htlc_id, payment_preimage) {
1678                                         Ok((msgs, monitor_option)) => {
1679                                                 if let Some(chan_monitor) = monitor_option {
1680                                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1681                                                                 unimplemented!();// but def dont push the event...
1682                                                         }
1683                                                 }
1684                                                 if let Some((msg, commitment_signed)) = msgs {
1685                                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1686                                                                 node_id: chan.get_their_node_id(),
1687                                                                 updates: msgs::CommitmentUpdate {
1688                                                                         update_add_htlcs: Vec::new(),
1689                                                                         update_fulfill_htlcs: vec![msg],
1690                                                                         update_fail_htlcs: Vec::new(),
1691                                                                         update_fail_malformed_htlcs: Vec::new(),
1692                                                                         update_fee: None,
1693                                                                         commitment_signed,
1694                                                                 }
1695                                                         });
1696                                                 }
1697                                         },
1698                                         Err(_e) => {
1699                                                 // TODO: There is probably a channel manager somewhere that needs to
1700                                                 // learn the preimage as the channel may be about to hit the chain.
1701                                                 //TODO: Do something with e?
1702                                                 return
1703                                         },
1704                                 }
1705                         },
1706                 }
1707         }
1708
1709         /// Gets the node_id held by this ChannelManager
1710         pub fn get_our_node_id(&self) -> PublicKey {
1711                 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
1712         }
1713
1714         /// Used to restore channels to normal operation after a
1715         /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
1716         /// operation.
1717         pub fn test_restore_channel_monitor(&self) {
1718                 let mut close_results = Vec::new();
1719                 let mut htlc_forwards = Vec::new();
1720                 let mut htlc_failures = Vec::new();
1721                 let _ = self.total_consistency_lock.read().unwrap();
1722
1723                 {
1724                         let mut channel_lock = self.channel_state.lock().unwrap();
1725                         let channel_state = channel_lock.borrow_parts();
1726                         let short_to_id = channel_state.short_to_id;
1727                         let pending_msg_events = channel_state.pending_msg_events;
1728                         channel_state.by_id.retain(|_, channel| {
1729                                 if channel.is_awaiting_monitor_update() {
1730                                         let chan_monitor = channel.channel_monitor();
1731                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1732                                                 match e {
1733                                                         ChannelMonitorUpdateErr::PermanentFailure => {
1734                                                                 // TODO: There may be some pending HTLCs that we intended to fail
1735                                                                 // backwards when a monitor update failed. We should make sure
1736                                                                 // knowledge of those gets moved into the appropriate in-memory
1737                                                                 // ChannelMonitor and they get failed backwards once we get
1738                                                                 // on-chain confirmations.
1739                                                                 // Note I think #198 addresses this, so once its merged a test
1740                                                                 // should be written.
1741                                                                 if let Some(short_id) = channel.get_short_channel_id() {
1742                                                                         short_to_id.remove(&short_id);
1743                                                                 }
1744                                                                 close_results.push(channel.force_shutdown());
1745                                                                 if let Ok(update) = self.get_channel_update(&channel) {
1746                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1747                                                                                 msg: update
1748                                                                         });
1749                                                                 }
1750                                                                 false
1751                                                         },
1752                                                         ChannelMonitorUpdateErr::TemporaryFailure => true,
1753                                                 }
1754                                         } else {
1755                                                 let (raa, commitment_update, order, pending_forwards, mut pending_failures) = channel.monitor_updating_restored();
1756                                                 if !pending_forwards.is_empty() {
1757                                                         htlc_forwards.push((channel.get_short_channel_id().expect("We can't have pending forwards before funding confirmation"), pending_forwards));
1758                                                 }
1759                                                 htlc_failures.append(&mut pending_failures);
1760
1761                                                 macro_rules! handle_cs { () => {
1762                                                         if let Some(update) = commitment_update {
1763                                                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1764                                                                         node_id: channel.get_their_node_id(),
1765                                                                         updates: update,
1766                                                                 });
1767                                                         }
1768                                                 } }
1769                                                 macro_rules! handle_raa { () => {
1770                                                         if let Some(revoke_and_ack) = raa {
1771                                                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
1772                                                                         node_id: channel.get_their_node_id(),
1773                                                                         msg: revoke_and_ack,
1774                                                                 });
1775                                                         }
1776                                                 } }
1777                                                 match order {
1778                                                         RAACommitmentOrder::CommitmentFirst => {
1779                                                                 handle_cs!();
1780                                                                 handle_raa!();
1781                                                         },
1782                                                         RAACommitmentOrder::RevokeAndACKFirst => {
1783                                                                 handle_raa!();
1784                                                                 handle_cs!();
1785                                                         },
1786                                                 }
1787                                                 true
1788                                         }
1789                                 } else { true }
1790                         });
1791                 }
1792
1793                 for failure in htlc_failures.drain(..) {
1794                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
1795                 }
1796                 self.forward_htlcs(&mut htlc_forwards[..]);
1797
1798                 for res in close_results.drain(..) {
1799                         self.finish_force_close_channel(res);
1800                 }
1801         }
1802
1803         fn internal_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
1804                 if msg.chain_hash != self.genesis_hash {
1805                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash", msg.temporary_channel_id.clone()));
1806                 }
1807
1808                 let channel = Channel::new_from_req(&*self.fee_estimator, &self.keys_manager, their_node_id.clone(), msg, 0, Arc::clone(&self.logger), &self.default_configuration)
1809                         .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
1810                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1811                 let channel_state = channel_state_lock.borrow_parts();
1812                 match channel_state.by_id.entry(channel.channel_id()) {
1813                         hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!", msg.temporary_channel_id.clone())),
1814                         hash_map::Entry::Vacant(entry) => {
1815                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
1816                                         node_id: their_node_id.clone(),
1817                                         msg: channel.get_accept_channel(),
1818                                 });
1819                                 entry.insert(channel);
1820                         }
1821                 }
1822                 Ok(())
1823         }
1824
1825         fn internal_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
1826                 let (value, output_script, user_id) = {
1827                         let mut channel_lock = self.channel_state.lock().unwrap();
1828                         let channel_state = channel_lock.borrow_parts();
1829                         match channel_state.by_id.entry(msg.temporary_channel_id) {
1830                                 hash_map::Entry::Occupied(mut chan) => {
1831                                         if chan.get().get_their_node_id() != *their_node_id {
1832                                                 //TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
1833                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1834                                         }
1835                                         try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration), channel_state, chan);
1836                                         (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
1837                                 },
1838                                 //TODO: same as above
1839                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1840                         }
1841                 };
1842                 let mut pending_events = self.pending_events.lock().unwrap();
1843                 pending_events.push(events::Event::FundingGenerationReady {
1844                         temporary_channel_id: msg.temporary_channel_id,
1845                         channel_value_satoshis: value,
1846                         output_script: output_script,
1847                         user_channel_id: user_id,
1848                 });
1849                 Ok(())
1850         }
1851
1852         fn internal_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
1853                 let ((funding_msg, monitor_update), chan) = {
1854                         let mut channel_lock = self.channel_state.lock().unwrap();
1855                         let channel_state = channel_lock.borrow_parts();
1856                         match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
1857                                 hash_map::Entry::Occupied(mut chan) => {
1858                                         if chan.get().get_their_node_id() != *their_node_id {
1859                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1860                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1861                                         }
1862                                         (try_chan_entry!(self, chan.get_mut().funding_created(msg), channel_state, chan), chan.remove())
1863                                 },
1864                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1865                         }
1866                 };
1867                 // Because we have exclusive ownership of the channel here we can release the channel_state
1868                 // lock before add_update_monitor
1869                 if let Err(_e) = self.monitor.add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) {
1870                         unimplemented!();
1871                 }
1872                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1873                 let channel_state = channel_state_lock.borrow_parts();
1874                 match channel_state.by_id.entry(funding_msg.channel_id) {
1875                         hash_map::Entry::Occupied(_) => {
1876                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id", funding_msg.channel_id))
1877                         },
1878                         hash_map::Entry::Vacant(e) => {
1879                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
1880                                         node_id: their_node_id.clone(),
1881                                         msg: funding_msg,
1882                                 });
1883                                 e.insert(chan);
1884                         }
1885                 }
1886                 Ok(())
1887         }
1888
1889         fn internal_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
1890                 let (funding_txo, user_id) = {
1891                         let mut channel_lock = self.channel_state.lock().unwrap();
1892                         let channel_state = channel_lock.borrow_parts();
1893                         match channel_state.by_id.entry(msg.channel_id) {
1894                                 hash_map::Entry::Occupied(mut chan) => {
1895                                         if chan.get().get_their_node_id() != *their_node_id {
1896                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1897                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1898                                         }
1899                                         let chan_monitor = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
1900                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1901                                                 unimplemented!();
1902                                         }
1903                                         (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())
1904                                 },
1905                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1906                         }
1907                 };
1908                 let mut pending_events = self.pending_events.lock().unwrap();
1909                 pending_events.push(events::Event::FundingBroadcastSafe {
1910                         funding_txo: funding_txo,
1911                         user_channel_id: user_id,
1912                 });
1913                 Ok(())
1914         }
1915
1916         fn internal_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), MsgHandleErrInternal> {
1917                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1918                 let channel_state = channel_state_lock.borrow_parts();
1919                 match channel_state.by_id.entry(msg.channel_id) {
1920                         hash_map::Entry::Occupied(mut chan) => {
1921                                 if chan.get().get_their_node_id() != *their_node_id {
1922                                         //TODO: here and below MsgHandleErrInternal, #153 case
1923                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1924                                 }
1925                                 try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
1926                                 if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
1927                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
1928                                                 node_id: their_node_id.clone(),
1929                                                 msg: announcement_sigs,
1930                                         });
1931                                 }
1932                                 Ok(())
1933                         },
1934                         hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1935                 }
1936         }
1937
1938         fn internal_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
1939                 let (mut dropped_htlcs, chan_option) = {
1940                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1941                         let channel_state = channel_state_lock.borrow_parts();
1942
1943                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1944                                 hash_map::Entry::Occupied(mut chan_entry) => {
1945                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1946                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1947                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1948                                         }
1949                                         let (shutdown, closing_signed, dropped_htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg), channel_state, chan_entry);
1950                                         if let Some(msg) = shutdown {
1951                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
1952                                                         node_id: their_node_id.clone(),
1953                                                         msg,
1954                                                 });
1955                                         }
1956                                         if let Some(msg) = closing_signed {
1957                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1958                                                         node_id: their_node_id.clone(),
1959                                                         msg,
1960                                                 });
1961                                         }
1962                                         if chan_entry.get().is_shutdown() {
1963                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1964                                                         channel_state.short_to_id.remove(&short_id);
1965                                                 }
1966                                                 (dropped_htlcs, Some(chan_entry.remove_entry().1))
1967                                         } else { (dropped_htlcs, None) }
1968                                 },
1969                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1970                         }
1971                 };
1972                 for htlc_source in dropped_htlcs.drain(..) {
1973                         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() });
1974                 }
1975                 if let Some(chan) = chan_option {
1976                         if let Ok(update) = self.get_channel_update(&chan) {
1977                                 let mut channel_state = self.channel_state.lock().unwrap();
1978                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1979                                         msg: update
1980                                 });
1981                         }
1982                 }
1983                 Ok(())
1984         }
1985
1986         fn internal_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
1987                 let (tx, chan_option) = {
1988                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1989                         let channel_state = channel_state_lock.borrow_parts();
1990                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1991                                 hash_map::Entry::Occupied(mut chan_entry) => {
1992                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1993                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1994                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1995                                         }
1996                                         let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg), channel_state, chan_entry);
1997                                         if let Some(msg) = closing_signed {
1998                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1999                                                         node_id: their_node_id.clone(),
2000                                                         msg,
2001                                                 });
2002                                         }
2003                                         if tx.is_some() {
2004                                                 // We're done with this channel, we've got a signed closing transaction and
2005                                                 // will send the closing_signed back to the remote peer upon return. This
2006                                                 // also implies there are no pending HTLCs left on the channel, so we can
2007                                                 // fully delete it from tracking (the channel monitor is still around to
2008                                                 // watch for old state broadcasts)!
2009                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2010                                                         channel_state.short_to_id.remove(&short_id);
2011                                                 }
2012                                                 (tx, Some(chan_entry.remove_entry().1))
2013                                         } else { (tx, None) }
2014                                 },
2015                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2016                         }
2017                 };
2018                 if let Some(broadcast_tx) = tx {
2019                         self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
2020                 }
2021                 if let Some(chan) = chan_option {
2022                         if let Ok(update) = self.get_channel_update(&chan) {
2023                                 let mut channel_state = self.channel_state.lock().unwrap();
2024                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2025                                         msg: update
2026                                 });
2027                         }
2028                 }
2029                 Ok(())
2030         }
2031
2032         fn internal_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
2033                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
2034                 //determine the state of the payment based on our response/if we forward anything/the time
2035                 //we take to respond. We should take care to avoid allowing such an attack.
2036                 //
2037                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
2038                 //us repeatedly garbled in different ways, and compare our error messages, which are
2039                 //encrypted with the same key. Its not immediately obvious how to usefully exploit that,
2040                 //but we should prevent it anyway.
2041
2042                 let (mut pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
2043                 let channel_state = channel_state_lock.borrow_parts();
2044
2045                 match channel_state.by_id.entry(msg.channel_id) {
2046                         hash_map::Entry::Occupied(mut chan) => {
2047                                 if chan.get().get_their_node_id() != *their_node_id {
2048                                         //TODO: here MsgHandleErrInternal, #153 case
2049                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2050                                 }
2051                                 if !chan.get().is_usable() {
2052                                         // If the update_add is completely bogus, the call will Err and we will close,
2053                                         // but if we've sent a shutdown and they haven't acknowledged it yet, we just
2054                                         // want to reject the new HTLC and fail it backwards instead of forwarding.
2055                                         if let PendingHTLCStatus::Forward(PendingForwardHTLCInfo { incoming_shared_secret, .. }) = pending_forward_info {
2056                                                 let chan_update = self.get_channel_update(chan.get());
2057                                                 pending_forward_info = PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
2058                                                         channel_id: msg.channel_id,
2059                                                         htlc_id: msg.htlc_id,
2060                                                         reason: if let Ok(update) = chan_update {
2061                                                                 // TODO: Note that |20 is defined as "channel FROM the processing
2062                                                                 // node has been disabled" (emphasis mine), which seems to imply
2063                                                                 // that we can't return |20 for an inbound channel being disabled.
2064                                                                 // This probably needs a spec update but should definitely be
2065                                                                 // allowed.
2066                                                                 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x1000|20, &{
2067                                                                         let mut res = Vec::with_capacity(8 + 128);
2068                                                                         res.extend_from_slice(&byte_utils::be16_to_array(update.contents.flags));
2069                                                                         res.extend_from_slice(&update.encode_with_len()[..]);
2070                                                                         res
2071                                                                 }[..])
2072                                                         } else {
2073                                                                 // This can only happen if the channel isn't in the fully-funded
2074                                                                 // state yet, implying our counterparty is trying to route payments
2075                                                                 // over the channel back to themselves (cause no one else should
2076                                                                 // know the short_id is a lightning channel yet). We should have no
2077                                                                 // problem just calling this unknown_next_peer
2078                                                                 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x4000|10, &[])
2079                                                         },
2080                                                 }));
2081                                         }
2082                                 }
2083                                 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info), channel_state, chan);
2084                         },
2085                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2086                 }
2087                 Ok(())
2088         }
2089
2090         fn internal_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
2091                 let mut channel_lock = self.channel_state.lock().unwrap();
2092                 let htlc_source = {
2093                         let channel_state = channel_lock.borrow_parts();
2094                         match channel_state.by_id.entry(msg.channel_id) {
2095                                 hash_map::Entry::Occupied(mut chan) => {
2096                                         if chan.get().get_their_node_id() != *their_node_id {
2097                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2098                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2099                                         }
2100                                         try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), channel_state, chan)
2101                                 },
2102                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2103                         }
2104                 };
2105                 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
2106                 Ok(())
2107         }
2108
2109         // Process failure we got back from upstream on a payment we sent. Returns update and a boolean
2110         // indicating that the payment itself failed
2111         fn process_onion_failure(&self, htlc_source: &HTLCSource, mut packet_decrypted: Vec<u8>) -> (Option<msgs::HTLCFailChannelUpdate>, bool, Option<u16>) {
2112                 if let &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } = htlc_source {
2113
2114                         let mut res = None;
2115                         let mut htlc_msat = *first_hop_htlc_msat;
2116                         let mut error_code_ret = None;
2117                         let mut next_route_hop_ix = 0;
2118                         let mut is_from_final_node = false;
2119
2120                         // Handle packed channel/node updates for passing back for the route handler
2121                         Self::construct_onion_keys_callback(&self.secp_ctx, route, session_priv, |shared_secret, _, _, route_hop| {
2122                                 next_route_hop_ix += 1;
2123                                 if res.is_some() { return; }
2124
2125                                 let amt_to_forward = htlc_msat - route_hop.fee_msat;
2126                                 htlc_msat = amt_to_forward;
2127
2128                                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret[..]);
2129
2130                                 let mut decryption_tmp = Vec::with_capacity(packet_decrypted.len());
2131                                 decryption_tmp.resize(packet_decrypted.len(), 0);
2132                                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
2133                                 chacha.process(&packet_decrypted, &mut decryption_tmp[..]);
2134                                 packet_decrypted = decryption_tmp;
2135
2136                                 is_from_final_node = route.hops.last().unwrap().pubkey == route_hop.pubkey;
2137
2138                                 if let Ok(err_packet) = msgs::DecodedOnionErrorPacket::read(&mut Cursor::new(&packet_decrypted)) {
2139                                         let um = ChannelManager::gen_um_from_shared_secret(&shared_secret[..]);
2140                                         let mut hmac = HmacEngine::<Sha256>::new(&um);
2141                                         hmac.input(&err_packet.encode()[32..]);
2142
2143                                         if fixed_time_eq(&Hmac::from_engine(hmac).into_inner(), &err_packet.hmac) {
2144                                                 if let Some(error_code_slice) = err_packet.failuremsg.get(0..2) {
2145                                                         const PERM: u16 = 0x4000;
2146                                                         const NODE: u16 = 0x2000;
2147                                                         const UPDATE: u16 = 0x1000;
2148
2149                                                         let error_code = byte_utils::slice_to_be16(&error_code_slice);
2150                                                         error_code_ret = Some(error_code);
2151
2152                                                         let (debug_field, debug_field_size) = errors::get_onion_debug_field(error_code);
2153
2154                                                         // indicate that payment parameter has failed and no need to
2155                                                         // update Route object
2156                                                         let payment_failed = (match error_code & 0xff {
2157                                                                 15|16|17|18|19 => true,
2158                                                                 _ => false,
2159                                                         } && is_from_final_node) // PERM bit observed below even this error is from the intermediate nodes
2160                                                         || error_code == 21; // Special case error 21 as the Route object is bogus, TODO: Maybe fail the node if the CLTV was reasonable?
2161
2162                                                         let mut fail_channel_update = None;
2163
2164                                                         if error_code & NODE == NODE {
2165                                                                 fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure { node_id: route_hop.pubkey, is_permanent: error_code & PERM == PERM });
2166                                                         }
2167                                                         else if error_code & PERM == PERM {
2168                                                                 fail_channel_update = if payment_failed {None} else {Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
2169                                                                         short_channel_id: route.hops[next_route_hop_ix - if next_route_hop_ix == route.hops.len() { 1 } else { 0 }].short_channel_id,
2170                                                                         is_permanent: true,
2171                                                                 })};
2172                                                         }
2173                                                         else if error_code & UPDATE == UPDATE {
2174                                                                 if let Some(update_len_slice) = err_packet.failuremsg.get(debug_field_size+2..debug_field_size+4) {
2175                                                                         let update_len = byte_utils::slice_to_be16(&update_len_slice) as usize;
2176                                                                         if let Some(update_slice) = err_packet.failuremsg.get(debug_field_size + 4..debug_field_size + 4 + update_len) {
2177                                                                                 if let Ok(chan_update) = msgs::ChannelUpdate::read(&mut Cursor::new(&update_slice)) {
2178                                                                                         // if channel_update should NOT have caused the failure:
2179                                                                                         // MAY treat the channel_update as invalid.
2180                                                                                         let is_chan_update_invalid = match error_code & 0xff {
2181                                                                                                 7 => false,
2182                                                                                                 11 => amt_to_forward > chan_update.contents.htlc_minimum_msat,
2183                                                                                                 12 => {
2184                                                                                                         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) });
2185                                                                                                         new_fee.is_some() && route_hop.fee_msat >= new_fee.unwrap()
2186                                                                                                 }
2187                                                                                                 13 => route_hop.cltv_expiry_delta as u16 >= chan_update.contents.cltv_expiry_delta,
2188                                                                                                 14 => false, // expiry_too_soon; always valid?
2189                                                                                                 20 => chan_update.contents.flags & 2 == 0,
2190                                                                                                 _ => false, // unknown error code; take channel_update as valid
2191                                                                                         };
2192                                                                                         fail_channel_update = if is_chan_update_invalid {
2193                                                                                                 // This probably indicates the node which forwarded
2194                                                                                                 // to the node in question corrupted something.
2195                                                                                                 Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
2196                                                                                                         short_channel_id: route_hop.short_channel_id,
2197                                                                                                         is_permanent: true,
2198                                                                                                 })
2199                                                                                         } else {
2200                                                                                                 Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {
2201                                                                                                         msg: chan_update,
2202                                                                                                 })
2203                                                                                         };
2204                                                                                 }
2205                                                                         }
2206                                                                 }
2207                                                                 if fail_channel_update.is_none() {
2208                                                                         // They provided an UPDATE which was obviously bogus, not worth
2209                                                                         // trying to relay through them anymore.
2210                                                                         fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2211                                                                                 node_id: route_hop.pubkey,
2212                                                                                 is_permanent: true,
2213                                                                         });
2214                                                                 }
2215                                                         } else if !payment_failed {
2216                                                                 // We can't understand their error messages and they failed to
2217                                                                 // forward...they probably can't understand our forwards so its
2218                                                                 // really not worth trying any further.
2219                                                                 fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2220                                                                         node_id: route_hop.pubkey,
2221                                                                         is_permanent: true,
2222                                                                 });
2223                                                         }
2224
2225                                                         // TODO: Here (and a few other places) we assume that BADONION errors
2226                                                         // are always "sourced" from the node previous to the one which failed
2227                                                         // to decode the onion.
2228                                                         res = Some((fail_channel_update, !(error_code & PERM == PERM && is_from_final_node)));
2229
2230                                                         let (description, title) = errors::get_onion_error_description(error_code);
2231                                                         if debug_field_size > 0 && err_packet.failuremsg.len() >= 4 + debug_field_size {
2232                                                                 log_warn!(self, "Onion Error[{}({:#x}) {}({})] {}", title, error_code, debug_field, log_bytes!(&err_packet.failuremsg[4..4+debug_field_size]), description);
2233                                                         }
2234                                                         else {
2235                                                                 log_warn!(self, "Onion Error[{}({:#x})] {}", title, error_code, description);
2236                                                         }
2237                                                 } else {
2238                                                         // Useless packet that we can't use but it passed HMAC, so it
2239                                                         // definitely came from the peer in question
2240                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2241                                                                 node_id: route_hop.pubkey,
2242                                                                 is_permanent: true,
2243                                                         }), !is_from_final_node));
2244                                                 }
2245                                         }
2246                                 }
2247                         }).expect("Route that we sent via spontaneously grew invalid keys in the middle of it?");
2248                         if let Some((channel_update, payment_retryable)) = res {
2249                                 (channel_update, payment_retryable, error_code_ret)
2250                         } else {
2251                                 // only not set either packet unparseable or hmac does not match with any
2252                                 // payment not retryable only when garbage is from the final node
2253                                 (None, !is_from_final_node, None)
2254                         }
2255                 } else { unreachable!(); }
2256         }
2257
2258         fn internal_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
2259                 let mut channel_lock = self.channel_state.lock().unwrap();
2260                 let channel_state = channel_lock.borrow_parts();
2261                 match channel_state.by_id.entry(msg.channel_id) {
2262                         hash_map::Entry::Occupied(mut chan) => {
2263                                 if chan.get().get_their_node_id() != *their_node_id {
2264                                         //TODO: here and below MsgHandleErrInternal, #153 case
2265                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2266                                 }
2267                                 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::ErrorPacket { err: msg.reason.clone() }), channel_state, chan);
2268                         },
2269                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2270                 }
2271                 Ok(())
2272         }
2273
2274         fn internal_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
2275                 let mut channel_lock = self.channel_state.lock().unwrap();
2276                 let channel_state = channel_lock.borrow_parts();
2277                 match channel_state.by_id.entry(msg.channel_id) {
2278                         hash_map::Entry::Occupied(mut chan) => {
2279                                 if chan.get().get_their_node_id() != *their_node_id {
2280                                         //TODO: here and below MsgHandleErrInternal, #153 case
2281                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2282                                 }
2283                                 if (msg.failure_code & 0x8000) == 0 {
2284                                         try_chan_entry!(self, Err(ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set")), channel_state, chan);
2285                                 }
2286                                 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);
2287                                 Ok(())
2288                         },
2289                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2290                 }
2291         }
2292
2293         fn internal_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
2294                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2295                 let channel_state = channel_state_lock.borrow_parts();
2296                 match channel_state.by_id.entry(msg.channel_id) {
2297                         hash_map::Entry::Occupied(mut chan) => {
2298                                 if chan.get().get_their_node_id() != *their_node_id {
2299                                         //TODO: here and below MsgHandleErrInternal, #153 case
2300                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2301                                 }
2302                                 let (revoke_and_ack, commitment_signed, closing_signed, chan_monitor) =
2303                                         try_chan_entry!(self, chan.get_mut().commitment_signed(&msg, &*self.fee_estimator), channel_state, chan);
2304                                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2305                                         return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, commitment_signed.is_some());
2306                                         //TODO: Rebroadcast closing_signed if present on monitor update restoration
2307                                 }
2308                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2309                                         node_id: their_node_id.clone(),
2310                                         msg: revoke_and_ack,
2311                                 });
2312                                 if let Some(msg) = commitment_signed {
2313                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2314                                                 node_id: their_node_id.clone(),
2315                                                 updates: msgs::CommitmentUpdate {
2316                                                         update_add_htlcs: Vec::new(),
2317                                                         update_fulfill_htlcs: Vec::new(),
2318                                                         update_fail_htlcs: Vec::new(),
2319                                                         update_fail_malformed_htlcs: Vec::new(),
2320                                                         update_fee: None,
2321                                                         commitment_signed: msg,
2322                                                 },
2323                                         });
2324                                 }
2325                                 if let Some(msg) = closing_signed {
2326                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2327                                                 node_id: their_node_id.clone(),
2328                                                 msg,
2329                                         });
2330                                 }
2331                                 Ok(())
2332                         },
2333                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2334                 }
2335         }
2336
2337         #[inline]
2338         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64)>)]) {
2339                 for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
2340                         let mut forward_event = None;
2341                         if !pending_forwards.is_empty() {
2342                                 let mut channel_state = self.channel_state.lock().unwrap();
2343                                 if channel_state.forward_htlcs.is_empty() {
2344                                         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));
2345                                         channel_state.next_forward = forward_event.unwrap();
2346                                 }
2347                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2348                                         match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
2349                                                 hash_map::Entry::Occupied(mut entry) => {
2350                                                         entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info });
2351                                                 },
2352                                                 hash_map::Entry::Vacant(entry) => {
2353                                                         entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info }));
2354                                                 }
2355                                         }
2356                                 }
2357                         }
2358                         match forward_event {
2359                                 Some(time) => {
2360                                         let mut pending_events = self.pending_events.lock().unwrap();
2361                                         pending_events.push(events::Event::PendingHTLCsForwardable {
2362                                                 time_forwardable: time
2363                                         });
2364                                 }
2365                                 None => {},
2366                         }
2367                 }
2368         }
2369
2370         fn internal_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
2371                 let (pending_forwards, mut pending_failures, short_channel_id) = {
2372                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2373                         let channel_state = channel_state_lock.borrow_parts();
2374                         match channel_state.by_id.entry(msg.channel_id) {
2375                                 hash_map::Entry::Occupied(mut chan) => {
2376                                         if chan.get().get_their_node_id() != *their_node_id {
2377                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2378                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2379                                         }
2380                                         let (commitment_update, pending_forwards, pending_failures, closing_signed, chan_monitor) =
2381                                                 try_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &*self.fee_estimator), channel_state, chan);
2382                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2383                                                 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, pending_forwards, pending_failures);
2384                                         }
2385                                         if let Some(updates) = commitment_update {
2386                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2387                                                         node_id: their_node_id.clone(),
2388                                                         updates,
2389                                                 });
2390                                         }
2391                                         if let Some(msg) = closing_signed {
2392                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2393                                                         node_id: their_node_id.clone(),
2394                                                         msg,
2395                                                 });
2396                                         }
2397                                         (pending_forwards, pending_failures, chan.get().get_short_channel_id().expect("RAA should only work on a short-id-available channel"))
2398                                 },
2399                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2400                         }
2401                 };
2402                 for failure in pending_failures.drain(..) {
2403                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2404                 }
2405                 self.forward_htlcs(&mut [(short_channel_id, pending_forwards)]);
2406
2407                 Ok(())
2408         }
2409
2410         fn internal_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2411                 let mut channel_lock = self.channel_state.lock().unwrap();
2412                 let channel_state = channel_lock.borrow_parts();
2413                 match channel_state.by_id.entry(msg.channel_id) {
2414                         hash_map::Entry::Occupied(mut chan) => {
2415                                 if chan.get().get_their_node_id() != *their_node_id {
2416                                         //TODO: here and below MsgHandleErrInternal, #153 case
2417                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2418                                 }
2419                                 try_chan_entry!(self, chan.get_mut().update_fee(&*self.fee_estimator, &msg), channel_state, chan);
2420                         },
2421                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2422                 }
2423                 Ok(())
2424         }
2425
2426         fn internal_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2427                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2428                 let channel_state = channel_state_lock.borrow_parts();
2429
2430                 match channel_state.by_id.entry(msg.channel_id) {
2431                         hash_map::Entry::Occupied(mut chan) => {
2432                                 if chan.get().get_their_node_id() != *their_node_id {
2433                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2434                                 }
2435                                 if !chan.get().is_usable() {
2436                                         return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Got an announcement_signatures before we were ready for it", action: Some(msgs::ErrorAction::IgnoreError)}));
2437                                 }
2438
2439                                 let our_node_id = self.get_our_node_id();
2440                                 let (announcement, our_bitcoin_sig) =
2441                                         try_chan_entry!(self, chan.get_mut().get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone()), channel_state, chan);
2442
2443                                 let were_node_one = announcement.node_id_1 == our_node_id;
2444                                 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
2445                                 if self.secp_ctx.verify(&msghash, &msg.node_signature, if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 }).is_err() ||
2446                                                 self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 }).is_err() {
2447                                         try_chan_entry!(self, Err(ChannelError::Close("Bad announcement_signatures node_signature")), channel_state, chan);
2448                                 }
2449
2450                                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2451
2452                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
2453                                         msg: msgs::ChannelAnnouncement {
2454                                                 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
2455                                                 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
2456                                                 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
2457                                                 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
2458                                                 contents: announcement,
2459                                         },
2460                                         update_msg: self.get_channel_update(chan.get()).unwrap(), // can only fail if we're not in a ready state
2461                                 });
2462                         },
2463                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2464                 }
2465                 Ok(())
2466         }
2467
2468         fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
2469                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2470                 let channel_state = channel_state_lock.borrow_parts();
2471
2472                 match channel_state.by_id.entry(msg.channel_id) {
2473                         hash_map::Entry::Occupied(mut chan) => {
2474                                 if chan.get().get_their_node_id() != *their_node_id {
2475                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2476                                 }
2477                                 let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, mut order, shutdown) =
2478                                         try_chan_entry!(self, chan.get_mut().channel_reestablish(msg), channel_state, chan);
2479                                 if let Some(monitor) = channel_monitor {
2480                                         if let Err(e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
2481                                                 // channel_reestablish doesn't guarantee the order it returns is sensical
2482                                                 // for the messages it returns, but if we're setting what messages to
2483                                                 // re-transmit on monitor update success, we need to make sure it is sane.
2484                                                 if revoke_and_ack.is_none() {
2485                                                         order = RAACommitmentOrder::CommitmentFirst;
2486                                                 }
2487                                                 if commitment_update.is_none() {
2488                                                         order = RAACommitmentOrder::RevokeAndACKFirst;
2489                                                 }
2490                                                 return_monitor_err!(self, e, channel_state, chan, order);
2491                                                 //TODO: Resend the funding_locked if needed once we get the monitor running again
2492                                         }
2493                                 }
2494                                 if let Some(msg) = funding_locked {
2495                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2496                                                 node_id: their_node_id.clone(),
2497                                                 msg
2498                                         });
2499                                 }
2500                                 macro_rules! send_raa { () => {
2501                                         if let Some(msg) = revoke_and_ack {
2502                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2503                                                         node_id: their_node_id.clone(),
2504                                                         msg
2505                                                 });
2506                                         }
2507                                 } }
2508                                 macro_rules! send_cu { () => {
2509                                         if let Some(updates) = commitment_update {
2510                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2511                                                         node_id: their_node_id.clone(),
2512                                                         updates
2513                                                 });
2514                                         }
2515                                 } }
2516                                 match order {
2517                                         RAACommitmentOrder::RevokeAndACKFirst => {
2518                                                 send_raa!();
2519                                                 send_cu!();
2520                                         },
2521                                         RAACommitmentOrder::CommitmentFirst => {
2522                                                 send_cu!();
2523                                                 send_raa!();
2524                                         },
2525                                 }
2526                                 if let Some(msg) = shutdown {
2527                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2528                                                 node_id: their_node_id.clone(),
2529                                                 msg,
2530                                         });
2531                                 }
2532                                 Ok(())
2533                         },
2534                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2535                 }
2536         }
2537
2538         /// Begin Update fee process. Allowed only on an outbound channel.
2539         /// If successful, will generate a UpdateHTLCs event, so you should probably poll
2540         /// PeerManager::process_events afterwards.
2541         /// Note: This API is likely to change!
2542         #[doc(hidden)]
2543         pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u64) -> Result<(), APIError> {
2544                 let _ = self.total_consistency_lock.read().unwrap();
2545                 let their_node_id;
2546                 let err: Result<(), _> = loop {
2547                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2548                         let channel_state = channel_state_lock.borrow_parts();
2549
2550                         match channel_state.by_id.entry(channel_id) {
2551                                 hash_map::Entry::Vacant(_) => return Err(APIError::APIMisuseError{err: "Failed to find corresponding channel"}),
2552                                 hash_map::Entry::Occupied(mut chan) => {
2553                                         if !chan.get().is_outbound() {
2554                                                 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel"});
2555                                         }
2556                                         if chan.get().is_awaiting_monitor_update() {
2557                                                 return Err(APIError::MonitorUpdateFailed);
2558                                         }
2559                                         if !chan.get().is_live() {
2560                                                 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected"});
2561                                         }
2562                                         their_node_id = chan.get().get_their_node_id();
2563                                         if let Some((update_fee, commitment_signed, chan_monitor)) =
2564                                                         break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw), channel_state, chan)
2565                                         {
2566                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2567                                                         unimplemented!();
2568                                                 }
2569                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2570                                                         node_id: chan.get().get_their_node_id(),
2571                                                         updates: msgs::CommitmentUpdate {
2572                                                                 update_add_htlcs: Vec::new(),
2573                                                                 update_fulfill_htlcs: Vec::new(),
2574                                                                 update_fail_htlcs: Vec::new(),
2575                                                                 update_fail_malformed_htlcs: Vec::new(),
2576                                                                 update_fee: Some(update_fee),
2577                                                                 commitment_signed,
2578                                                         },
2579                                                 });
2580                                         }
2581                                 },
2582                         }
2583                         return Ok(())
2584                 };
2585
2586                 match handle_error!(self, err, their_node_id) {
2587                         Ok(_) => unreachable!(),
2588                         Err(e) => {
2589                                 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
2590                                 } else {
2591                                         log_error!(self, "Got bad keys: {}!", e.err);
2592                                         let mut channel_state = self.channel_state.lock().unwrap();
2593                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
2594                                                 node_id: their_node_id,
2595                                                 action: e.action,
2596                                         });
2597                                 }
2598                                 Err(APIError::APIMisuseError { err: e.err })
2599                         },
2600                 }
2601         }
2602 }
2603
2604 impl events::MessageSendEventsProvider for ChannelManager {
2605         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
2606                 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2607                 // user to serialize a ChannelManager with pending events in it and lose those events on
2608                 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2609                 {
2610                         //TODO: This behavior should be documented.
2611                         for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2612                                 if let Some(preimage) = htlc_update.payment_preimage {
2613                                         log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2614                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2615                                 } else {
2616                                         log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2617                                         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() });
2618                                 }
2619                         }
2620                 }
2621
2622                 let mut ret = Vec::new();
2623                 let mut channel_state = self.channel_state.lock().unwrap();
2624                 mem::swap(&mut ret, &mut channel_state.pending_msg_events);
2625                 ret
2626         }
2627 }
2628
2629 impl events::EventsProvider for ChannelManager {
2630         fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
2631                 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2632                 // user to serialize a ChannelManager with pending events in it and lose those events on
2633                 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2634                 {
2635                         //TODO: This behavior should be documented.
2636                         for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2637                                 if let Some(preimage) = htlc_update.payment_preimage {
2638                                         log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2639                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2640                                 } else {
2641                                         log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2642                                         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() });
2643                                 }
2644                         }
2645                 }
2646
2647                 let mut ret = Vec::new();
2648                 let mut pending_events = self.pending_events.lock().unwrap();
2649                 mem::swap(&mut ret, &mut *pending_events);
2650                 ret
2651         }
2652 }
2653
2654 impl ChainListener for ChannelManager {
2655         fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
2656                 let header_hash = header.bitcoin_hash();
2657                 log_trace!(self, "Block {} at height {} connected with {} txn matched", header_hash, height, txn_matched.len());
2658                 let _ = self.total_consistency_lock.read().unwrap();
2659                 let mut failed_channels = Vec::new();
2660                 {
2661                         let mut channel_lock = self.channel_state.lock().unwrap();
2662                         let channel_state = channel_lock.borrow_parts();
2663                         let short_to_id = channel_state.short_to_id;
2664                         let pending_msg_events = channel_state.pending_msg_events;
2665                         channel_state.by_id.retain(|_, channel| {
2666                                 let chan_res = channel.block_connected(header, height, txn_matched, indexes_of_txn_matched);
2667                                 if let Ok(Some(funding_locked)) = chan_res {
2668                                         pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2669                                                 node_id: channel.get_their_node_id(),
2670                                                 msg: funding_locked,
2671                                         });
2672                                         if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
2673                                                 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2674                                                         node_id: channel.get_their_node_id(),
2675                                                         msg: announcement_sigs,
2676                                                 });
2677                                         }
2678                                         short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
2679                                 } else if let Err(e) = chan_res {
2680                                         pending_msg_events.push(events::MessageSendEvent::HandleError {
2681                                                 node_id: channel.get_their_node_id(),
2682                                                 action: Some(msgs::ErrorAction::SendErrorMessage { msg: e }),
2683                                         });
2684                                         return false;
2685                                 }
2686                                 if let Some(funding_txo) = channel.get_funding_txo() {
2687                                         for tx in txn_matched {
2688                                                 for inp in tx.input.iter() {
2689                                                         if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
2690                                                                 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()));
2691                                                                 if let Some(short_id) = channel.get_short_channel_id() {
2692                                                                         short_to_id.remove(&short_id);
2693                                                                 }
2694                                                                 // It looks like our counterparty went on-chain. We go ahead and
2695                                                                 // broadcast our latest local state as well here, just in case its
2696                                                                 // some kind of SPV attack, though we expect these to be dropped.
2697                                                                 failed_channels.push(channel.force_shutdown());
2698                                                                 if let Ok(update) = self.get_channel_update(&channel) {
2699                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2700                                                                                 msg: update
2701                                                                         });
2702                                                                 }
2703                                                                 return false;
2704                                                         }
2705                                                 }
2706                                         }
2707                                 }
2708                                 if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height) {
2709                                         if let Some(short_id) = channel.get_short_channel_id() {
2710                                                 short_to_id.remove(&short_id);
2711                                         }
2712                                         failed_channels.push(channel.force_shutdown());
2713                                         // If would_broadcast_at_height() is true, the channel_monitor will broadcast
2714                                         // the latest local tx for us, so we should skip that here (it doesn't really
2715                                         // hurt anything, but does make tests a bit simpler).
2716                                         failed_channels.last_mut().unwrap().0 = Vec::new();
2717                                         if let Ok(update) = self.get_channel_update(&channel) {
2718                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2719                                                         msg: update
2720                                                 });
2721                                         }
2722                                         return false;
2723                                 }
2724                                 true
2725                         });
2726                 }
2727                 for failure in failed_channels.drain(..) {
2728                         self.finish_force_close_channel(failure);
2729                 }
2730                 self.latest_block_height.store(height as usize, Ordering::Release);
2731                 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header_hash;
2732         }
2733
2734         /// We force-close the channel without letting our counterparty participate in the shutdown
2735         fn block_disconnected(&self, header: &BlockHeader) {
2736                 let _ = self.total_consistency_lock.read().unwrap();
2737                 let mut failed_channels = Vec::new();
2738                 {
2739                         let mut channel_lock = self.channel_state.lock().unwrap();
2740                         let channel_state = channel_lock.borrow_parts();
2741                         let short_to_id = channel_state.short_to_id;
2742                         let pending_msg_events = channel_state.pending_msg_events;
2743                         channel_state.by_id.retain(|_,  v| {
2744                                 if v.block_disconnected(header) {
2745                                         if let Some(short_id) = v.get_short_channel_id() {
2746                                                 short_to_id.remove(&short_id);
2747                                         }
2748                                         failed_channels.push(v.force_shutdown());
2749                                         if let Ok(update) = self.get_channel_update(&v) {
2750                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2751                                                         msg: update
2752                                                 });
2753                                         }
2754                                         false
2755                                 } else {
2756                                         true
2757                                 }
2758                         });
2759                 }
2760                 for failure in failed_channels.drain(..) {
2761                         self.finish_force_close_channel(failure);
2762                 }
2763                 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
2764                 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
2765         }
2766 }
2767
2768 impl ChannelMessageHandler for ChannelManager {
2769         //TODO: Handle errors and close channel (or so)
2770         fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), HandleError> {
2771                 let _ = self.total_consistency_lock.read().unwrap();
2772                 handle_error!(self, self.internal_open_channel(their_node_id, msg), their_node_id)
2773         }
2774
2775         fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), HandleError> {
2776                 let _ = self.total_consistency_lock.read().unwrap();
2777                 handle_error!(self, self.internal_accept_channel(their_node_id, msg), their_node_id)
2778         }
2779
2780         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), HandleError> {
2781                 let _ = self.total_consistency_lock.read().unwrap();
2782                 handle_error!(self, self.internal_funding_created(their_node_id, msg), their_node_id)
2783         }
2784
2785         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), HandleError> {
2786                 let _ = self.total_consistency_lock.read().unwrap();
2787                 handle_error!(self, self.internal_funding_signed(their_node_id, msg), their_node_id)
2788         }
2789
2790         fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), HandleError> {
2791                 let _ = self.total_consistency_lock.read().unwrap();
2792                 handle_error!(self, self.internal_funding_locked(their_node_id, msg), their_node_id)
2793         }
2794
2795         fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), HandleError> {
2796                 let _ = self.total_consistency_lock.read().unwrap();
2797                 handle_error!(self, self.internal_shutdown(their_node_id, msg), their_node_id)
2798         }
2799
2800         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), HandleError> {
2801                 let _ = self.total_consistency_lock.read().unwrap();
2802                 handle_error!(self, self.internal_closing_signed(their_node_id, msg), their_node_id)
2803         }
2804
2805         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), msgs::HandleError> {
2806                 let _ = self.total_consistency_lock.read().unwrap();
2807                 handle_error!(self, self.internal_update_add_htlc(their_node_id, msg), their_node_id)
2808         }
2809
2810         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), HandleError> {
2811                 let _ = self.total_consistency_lock.read().unwrap();
2812                 handle_error!(self, self.internal_update_fulfill_htlc(their_node_id, msg), their_node_id)
2813         }
2814
2815         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), HandleError> {
2816                 let _ = self.total_consistency_lock.read().unwrap();
2817                 handle_error!(self, self.internal_update_fail_htlc(their_node_id, msg), their_node_id)
2818         }
2819
2820         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), HandleError> {
2821                 let _ = self.total_consistency_lock.read().unwrap();
2822                 handle_error!(self, self.internal_update_fail_malformed_htlc(their_node_id, msg), their_node_id)
2823         }
2824
2825         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), HandleError> {
2826                 let _ = self.total_consistency_lock.read().unwrap();
2827                 handle_error!(self, self.internal_commitment_signed(their_node_id, msg), their_node_id)
2828         }
2829
2830         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), HandleError> {
2831                 let _ = self.total_consistency_lock.read().unwrap();
2832                 handle_error!(self, self.internal_revoke_and_ack(their_node_id, msg), their_node_id)
2833         }
2834
2835         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), HandleError> {
2836                 let _ = self.total_consistency_lock.read().unwrap();
2837                 handle_error!(self, self.internal_update_fee(their_node_id, msg), their_node_id)
2838         }
2839
2840         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), HandleError> {
2841                 let _ = self.total_consistency_lock.read().unwrap();
2842                 handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
2843         }
2844
2845         fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), HandleError> {
2846                 let _ = self.total_consistency_lock.read().unwrap();
2847                 handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), their_node_id)
2848         }
2849
2850         fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
2851                 let _ = self.total_consistency_lock.read().unwrap();
2852                 let mut failed_channels = Vec::new();
2853                 let mut failed_payments = Vec::new();
2854                 {
2855                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2856                         let channel_state = channel_state_lock.borrow_parts();
2857                         let short_to_id = channel_state.short_to_id;
2858                         let pending_msg_events = channel_state.pending_msg_events;
2859                         if no_connection_possible {
2860                                 log_debug!(self, "Failing all channels with {} due to no_connection_possible", log_pubkey!(their_node_id));
2861                                 channel_state.by_id.retain(|_, chan| {
2862                                         if chan.get_their_node_id() == *their_node_id {
2863                                                 if let Some(short_id) = chan.get_short_channel_id() {
2864                                                         short_to_id.remove(&short_id);
2865                                                 }
2866                                                 failed_channels.push(chan.force_shutdown());
2867                                                 if let Ok(update) = self.get_channel_update(&chan) {
2868                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2869                                                                 msg: update
2870                                                         });
2871                                                 }
2872                                                 false
2873                                         } else {
2874                                                 true
2875                                         }
2876                                 });
2877                         } else {
2878                                 log_debug!(self, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(their_node_id));
2879                                 channel_state.by_id.retain(|_, chan| {
2880                                         if chan.get_their_node_id() == *their_node_id {
2881                                                 //TODO: mark channel disabled (and maybe announce such after a timeout).
2882                                                 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused();
2883                                                 if !failed_adds.is_empty() {
2884                                                         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
2885                                                         failed_payments.push((chan_update, failed_adds));
2886                                                 }
2887                                                 if chan.is_shutdown() {
2888                                                         if let Some(short_id) = chan.get_short_channel_id() {
2889                                                                 short_to_id.remove(&short_id);
2890                                                         }
2891                                                         return false;
2892                                                 }
2893                                         }
2894                                         true
2895                                 })
2896                         }
2897                 }
2898                 for failure in failed_channels.drain(..) {
2899                         self.finish_force_close_channel(failure);
2900                 }
2901                 for (chan_update, mut htlc_sources) in failed_payments {
2902                         for (htlc_source, payment_hash) in htlc_sources.drain(..) {
2903                                 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
2904                         }
2905                 }
2906         }
2907
2908         fn peer_connected(&self, their_node_id: &PublicKey) {
2909                 log_debug!(self, "Generating channel_reestablish events for {}", log_pubkey!(their_node_id));
2910
2911                 let _ = self.total_consistency_lock.read().unwrap();
2912                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2913                 let channel_state = channel_state_lock.borrow_parts();
2914                 let pending_msg_events = channel_state.pending_msg_events;
2915                 channel_state.by_id.retain(|_, chan| {
2916                         if chan.get_their_node_id() == *their_node_id {
2917                                 if !chan.have_received_message() {
2918                                         // If we created this (outbound) channel while we were disconnected from the
2919                                         // peer we probably failed to send the open_channel message, which is now
2920                                         // lost. We can't have had anything pending related to this channel, so we just
2921                                         // drop it.
2922                                         false
2923                                 } else {
2924                                         pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
2925                                                 node_id: chan.get_their_node_id(),
2926                                                 msg: chan.get_channel_reestablish(),
2927                                         });
2928                                         true
2929                                 }
2930                         } else { true }
2931                 });
2932                 //TODO: Also re-broadcast announcement_signatures
2933         }
2934
2935         fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
2936                 let _ = self.total_consistency_lock.read().unwrap();
2937
2938                 if msg.channel_id == [0; 32] {
2939                         for chan in self.list_channels() {
2940                                 if chan.remote_network_id == *their_node_id {
2941                                         self.force_close_channel(&chan.channel_id);
2942                                 }
2943                         }
2944                 } else {
2945                         self.force_close_channel(&msg.channel_id);
2946                 }
2947         }
2948 }
2949
2950 const SERIALIZATION_VERSION: u8 = 1;
2951 const MIN_SERIALIZATION_VERSION: u8 = 1;
2952
2953 impl Writeable for PendingForwardHTLCInfo {
2954         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2955                 if let &Some(ref onion) = &self.onion_packet {
2956                         1u8.write(writer)?;
2957                         onion.write(writer)?;
2958                 } else {
2959                         0u8.write(writer)?;
2960                 }
2961                 self.incoming_shared_secret.write(writer)?;
2962                 self.payment_hash.write(writer)?;
2963                 self.short_channel_id.write(writer)?;
2964                 self.amt_to_forward.write(writer)?;
2965                 self.outgoing_cltv_value.write(writer)?;
2966                 Ok(())
2967         }
2968 }
2969
2970 impl<R: ::std::io::Read> Readable<R> for PendingForwardHTLCInfo {
2971         fn read(reader: &mut R) -> Result<PendingForwardHTLCInfo, DecodeError> {
2972                 let onion_packet = match <u8 as Readable<R>>::read(reader)? {
2973                         0 => None,
2974                         1 => Some(msgs::OnionPacket::read(reader)?),
2975                         _ => return Err(DecodeError::InvalidValue),
2976                 };
2977                 Ok(PendingForwardHTLCInfo {
2978                         onion_packet,
2979                         incoming_shared_secret: Readable::read(reader)?,
2980                         payment_hash: Readable::read(reader)?,
2981                         short_channel_id: Readable::read(reader)?,
2982                         amt_to_forward: Readable::read(reader)?,
2983                         outgoing_cltv_value: Readable::read(reader)?,
2984                 })
2985         }
2986 }
2987
2988 impl Writeable for HTLCFailureMsg {
2989         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2990                 match self {
2991                         &HTLCFailureMsg::Relay(ref fail_msg) => {
2992                                 0u8.write(writer)?;
2993                                 fail_msg.write(writer)?;
2994                         },
2995                         &HTLCFailureMsg::Malformed(ref fail_msg) => {
2996                                 1u8.write(writer)?;
2997                                 fail_msg.write(writer)?;
2998                         }
2999                 }
3000                 Ok(())
3001         }
3002 }
3003
3004 impl<R: ::std::io::Read> Readable<R> for HTLCFailureMsg {
3005         fn read(reader: &mut R) -> Result<HTLCFailureMsg, DecodeError> {
3006                 match <u8 as Readable<R>>::read(reader)? {
3007                         0 => Ok(HTLCFailureMsg::Relay(Readable::read(reader)?)),
3008                         1 => Ok(HTLCFailureMsg::Malformed(Readable::read(reader)?)),
3009                         _ => Err(DecodeError::InvalidValue),
3010                 }
3011         }
3012 }
3013
3014 impl Writeable for PendingHTLCStatus {
3015         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3016                 match self {
3017                         &PendingHTLCStatus::Forward(ref forward_info) => {
3018                                 0u8.write(writer)?;
3019                                 forward_info.write(writer)?;
3020                         },
3021                         &PendingHTLCStatus::Fail(ref fail_msg) => {
3022                                 1u8.write(writer)?;
3023                                 fail_msg.write(writer)?;
3024                         }
3025                 }
3026                 Ok(())
3027         }
3028 }
3029
3030 impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
3031         fn read(reader: &mut R) -> Result<PendingHTLCStatus, DecodeError> {
3032                 match <u8 as Readable<R>>::read(reader)? {
3033                         0 => Ok(PendingHTLCStatus::Forward(Readable::read(reader)?)),
3034                         1 => Ok(PendingHTLCStatus::Fail(Readable::read(reader)?)),
3035                         _ => Err(DecodeError::InvalidValue),
3036                 }
3037         }
3038 }
3039
3040 impl_writeable!(HTLCPreviousHopData, 0, {
3041         short_channel_id,
3042         htlc_id,
3043         incoming_packet_shared_secret
3044 });
3045
3046 impl Writeable for HTLCSource {
3047         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3048                 match self {
3049                         &HTLCSource::PreviousHopData(ref hop_data) => {
3050                                 0u8.write(writer)?;
3051                                 hop_data.write(writer)?;
3052                         },
3053                         &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } => {
3054                                 1u8.write(writer)?;
3055                                 route.write(writer)?;
3056                                 session_priv.write(writer)?;
3057                                 first_hop_htlc_msat.write(writer)?;
3058                         }
3059                 }
3060                 Ok(())
3061         }
3062 }
3063
3064 impl<R: ::std::io::Read> Readable<R> for HTLCSource {
3065         fn read(reader: &mut R) -> Result<HTLCSource, DecodeError> {
3066                 match <u8 as Readable<R>>::read(reader)? {
3067                         0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
3068                         1 => Ok(HTLCSource::OutboundRoute {
3069                                 route: Readable::read(reader)?,
3070                                 session_priv: Readable::read(reader)?,
3071                                 first_hop_htlc_msat: Readable::read(reader)?,
3072                         }),
3073                         _ => Err(DecodeError::InvalidValue),
3074                 }
3075         }
3076 }
3077
3078 impl Writeable for HTLCFailReason {
3079         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3080                 match self {
3081                         &HTLCFailReason::ErrorPacket { ref err } => {
3082                                 0u8.write(writer)?;
3083                                 err.write(writer)?;
3084                         },
3085                         &HTLCFailReason::Reason { ref failure_code, ref data } => {
3086                                 1u8.write(writer)?;
3087                                 failure_code.write(writer)?;
3088                                 data.write(writer)?;
3089                         }
3090                 }
3091                 Ok(())
3092         }
3093 }
3094
3095 impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
3096         fn read(reader: &mut R) -> Result<HTLCFailReason, DecodeError> {
3097                 match <u8 as Readable<R>>::read(reader)? {
3098                         0 => Ok(HTLCFailReason::ErrorPacket { err: Readable::read(reader)? }),
3099                         1 => Ok(HTLCFailReason::Reason {
3100                                 failure_code: Readable::read(reader)?,
3101                                 data: Readable::read(reader)?,
3102                         }),
3103                         _ => Err(DecodeError::InvalidValue),
3104                 }
3105         }
3106 }
3107
3108 impl_writeable!(HTLCForwardInfo, 0, {
3109         prev_short_channel_id,
3110         prev_htlc_id,
3111         forward_info
3112 });
3113
3114 impl Writeable for ChannelManager {
3115         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3116                 let _ = self.total_consistency_lock.write().unwrap();
3117
3118                 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
3119                 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
3120
3121                 self.genesis_hash.write(writer)?;
3122                 (self.latest_block_height.load(Ordering::Acquire) as u32).write(writer)?;
3123                 self.last_block_hash.lock().unwrap().write(writer)?;
3124
3125                 let channel_state = self.channel_state.lock().unwrap();
3126                 let mut unfunded_channels = 0;
3127                 for (_, channel) in channel_state.by_id.iter() {
3128                         if !channel.is_funding_initiated() {
3129                                 unfunded_channels += 1;
3130                         }
3131                 }
3132                 ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
3133                 for (_, channel) in channel_state.by_id.iter() {
3134                         if channel.is_funding_initiated() {
3135                                 channel.write(writer)?;
3136                         }
3137                 }
3138
3139                 (channel_state.forward_htlcs.len() as u64).write(writer)?;
3140                 for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
3141                         short_channel_id.write(writer)?;
3142                         (pending_forwards.len() as u64).write(writer)?;
3143                         for forward in pending_forwards {
3144                                 forward.write(writer)?;
3145                         }
3146                 }
3147
3148                 (channel_state.claimable_htlcs.len() as u64).write(writer)?;
3149                 for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
3150                         payment_hash.write(writer)?;
3151                         (previous_hops.len() as u64).write(writer)?;
3152                         for previous_hop in previous_hops {
3153                                 previous_hop.write(writer)?;
3154                         }
3155                 }
3156
3157                 Ok(())
3158         }
3159 }
3160
3161 /// Arguments for the creation of a ChannelManager that are not deserialized.
3162 ///
3163 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
3164 /// is:
3165 /// 1) Deserialize all stored ChannelMonitors.
3166 /// 2) Deserialize the ChannelManager by filling in this struct and calling <(Sha256dHash,
3167 ///    ChannelManager)>::read(reader, args).
3168 ///    This may result in closing some Channels if the ChannelMonitor is newer than the stored
3169 ///    ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
3170 /// 3) Register all relevant ChannelMonitor outpoints with your chain watch mechanism using
3171 ///    ChannelMonitor::get_monitored_outpoints and ChannelMonitor::get_funding_txo().
3172 /// 4) Reconnect blocks on your ChannelMonitors.
3173 /// 5) Move the ChannelMonitors into your local ManyChannelMonitor.
3174 /// 6) Disconnect/connect blocks on the ChannelManager.
3175 /// 7) Register the new ChannelManager with your ChainWatchInterface (this does not happen
3176 ///    automatically as it does in ChannelManager::new()).
3177 pub struct ChannelManagerReadArgs<'a> {
3178         /// The keys provider which will give us relevant keys. Some keys will be loaded during
3179         /// deserialization.
3180         pub keys_manager: Arc<KeysInterface>,
3181
3182         /// The fee_estimator for use in the ChannelManager in the future.
3183         ///
3184         /// No calls to the FeeEstimator will be made during deserialization.
3185         pub fee_estimator: Arc<FeeEstimator>,
3186         /// The ManyChannelMonitor for use in the ChannelManager in the future.
3187         ///
3188         /// No calls to the ManyChannelMonitor will be made during deserialization. It is assumed that
3189         /// you have deserialized ChannelMonitors separately and will add them to your
3190         /// ManyChannelMonitor after deserializing this ChannelManager.
3191         pub monitor: Arc<ManyChannelMonitor>,
3192         /// The ChainWatchInterface for use in the ChannelManager in the future.
3193         ///
3194         /// No calls to the ChainWatchInterface will be made during deserialization.
3195         pub chain_monitor: Arc<ChainWatchInterface>,
3196         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
3197         /// used to broadcast the latest local commitment transactions of channels which must be
3198         /// force-closed during deserialization.
3199         pub tx_broadcaster: Arc<BroadcasterInterface>,
3200         /// The Logger for use in the ChannelManager and which may be used to log information during
3201         /// deserialization.
3202         pub logger: Arc<Logger>,
3203         /// Default settings used for new channels. Any existing channels will continue to use the
3204         /// runtime settings which were stored when the ChannelManager was serialized.
3205         pub default_config: UserConfig,
3206
3207         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
3208         /// value.get_funding_txo() should be the key).
3209         ///
3210         /// If a monitor is inconsistent with the channel state during deserialization the channel will
3211         /// be force-closed using the data in the channelmonitor and the Channel will be dropped. This
3212         /// is true for missing channels as well. If there is a monitor missing for which we find
3213         /// channel data Err(DecodeError::InvalidValue) will be returned.
3214         ///
3215         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
3216         /// this struct.
3217         pub channel_monitors: &'a HashMap<OutPoint, &'a ChannelMonitor>,
3218 }
3219
3220 impl<'a, R : ::std::io::Read> ReadableArgs<R, ChannelManagerReadArgs<'a>> for (Sha256dHash, ChannelManager) {
3221         fn read(reader: &mut R, args: ChannelManagerReadArgs<'a>) -> Result<Self, DecodeError> {
3222                 let _ver: u8 = Readable::read(reader)?;
3223                 let min_ver: u8 = Readable::read(reader)?;
3224                 if min_ver > SERIALIZATION_VERSION {
3225                         return Err(DecodeError::UnknownVersion);
3226                 }
3227
3228                 let genesis_hash: Sha256dHash = Readable::read(reader)?;
3229                 let latest_block_height: u32 = Readable::read(reader)?;
3230                 let last_block_hash: Sha256dHash = Readable::read(reader)?;
3231
3232                 let mut closed_channels = Vec::new();
3233
3234                 let channel_count: u64 = Readable::read(reader)?;
3235                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
3236                 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3237                 let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3238                 for _ in 0..channel_count {
3239                         let mut channel: Channel = ReadableArgs::read(reader, args.logger.clone())?;
3240                         if channel.last_block_connected != last_block_hash {
3241                                 return Err(DecodeError::InvalidValue);
3242                         }
3243
3244                         let funding_txo = channel.channel_monitor().get_funding_txo().ok_or(DecodeError::InvalidValue)?;
3245                         funding_txo_set.insert(funding_txo.clone());
3246                         if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
3247                                 if channel.get_cur_local_commitment_transaction_number() != monitor.get_cur_local_commitment_number() ||
3248                                                 channel.get_revoked_remote_commitment_transaction_number() != monitor.get_min_seen_secret() ||
3249                                                 channel.get_cur_remote_commitment_transaction_number() != monitor.get_cur_remote_commitment_number() {
3250                                         let mut force_close_res = channel.force_shutdown();
3251                                         force_close_res.0 = monitor.get_latest_local_commitment_txn();
3252                                         closed_channels.push(force_close_res);
3253                                 } else {
3254                                         if let Some(short_channel_id) = channel.get_short_channel_id() {
3255                                                 short_to_id.insert(short_channel_id, channel.channel_id());
3256                                         }
3257                                         by_id.insert(channel.channel_id(), channel);
3258                                 }
3259                         } else {
3260                                 return Err(DecodeError::InvalidValue);
3261                         }
3262                 }
3263
3264                 for (ref funding_txo, ref monitor) in args.channel_monitors.iter() {
3265                         if !funding_txo_set.contains(funding_txo) {
3266                                 closed_channels.push((monitor.get_latest_local_commitment_txn(), Vec::new()));
3267                         }
3268                 }
3269
3270                 let forward_htlcs_count: u64 = Readable::read(reader)?;
3271                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
3272                 for _ in 0..forward_htlcs_count {
3273                         let short_channel_id = Readable::read(reader)?;
3274                         let pending_forwards_count: u64 = Readable::read(reader)?;
3275                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, 128));
3276                         for _ in 0..pending_forwards_count {
3277                                 pending_forwards.push(Readable::read(reader)?);
3278                         }
3279                         forward_htlcs.insert(short_channel_id, pending_forwards);
3280                 }
3281
3282                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
3283                 let mut claimable_htlcs = HashMap::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
3284                 for _ in 0..claimable_htlcs_count {
3285                         let payment_hash = Readable::read(reader)?;
3286                         let previous_hops_len: u64 = Readable::read(reader)?;
3287                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, 2));
3288                         for _ in 0..previous_hops_len {
3289                                 previous_hops.push(Readable::read(reader)?);
3290                         }
3291                         claimable_htlcs.insert(payment_hash, previous_hops);
3292                 }
3293
3294                 let channel_manager = ChannelManager {
3295                         genesis_hash,
3296                         fee_estimator: args.fee_estimator,
3297                         monitor: args.monitor,
3298                         chain_monitor: args.chain_monitor,
3299                         tx_broadcaster: args.tx_broadcaster,
3300
3301                         latest_block_height: AtomicUsize::new(latest_block_height as usize),
3302                         last_block_hash: Mutex::new(last_block_hash),
3303                         secp_ctx: Secp256k1::new(),
3304
3305                         channel_state: Mutex::new(ChannelHolder {
3306                                 by_id,
3307                                 short_to_id,
3308                                 next_forward: Instant::now(),
3309                                 forward_htlcs,
3310                                 claimable_htlcs,
3311                                 pending_msg_events: Vec::new(),
3312                         }),
3313                         our_network_key: args.keys_manager.get_node_secret(),
3314
3315                         pending_events: Mutex::new(Vec::new()),
3316                         total_consistency_lock: RwLock::new(()),
3317                         keys_manager: args.keys_manager,
3318                         logger: args.logger,
3319                         default_configuration: args.default_config,
3320                 };
3321
3322                 for close_res in closed_channels.drain(..) {
3323                         channel_manager.finish_force_close_channel(close_res);
3324                         //TODO: Broadcast channel update for closed channels, but only after we've made a
3325                         //connection or two.
3326                 }
3327
3328                 Ok((last_block_hash.clone(), channel_manager))
3329         }
3330 }
3331
3332 #[cfg(test)]
3333 mod tests {
3334         use chain::chaininterface;
3335         use chain::transaction::OutPoint;
3336         use chain::chaininterface::{ChainListener, ChainWatchInterface};
3337         use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor};
3338         use chain::keysinterface;
3339         use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
3340         use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,OnionKeys,RAACommitmentOrder, PaymentPreimage, PaymentHash};
3341         use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, ManyChannelMonitor};
3342         use ln::channel::{ACCEPTED_HTLC_SCRIPT_WEIGHT, OFFERED_HTLC_SCRIPT_WEIGHT};
3343         use ln::router::{Route, RouteHop, Router};
3344         use ln::msgs;
3345         use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate};
3346         use util::test_utils;
3347         use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
3348         use util::errors::APIError;
3349         use util::logger::Logger;
3350         use util::ser::{Writeable, Writer, ReadableArgs};
3351         use util::config::UserConfig;
3352
3353         use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
3354         use bitcoin::util::bip143;
3355         use bitcoin::util::address::Address;
3356         use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
3357         use bitcoin::blockdata::block::{Block, BlockHeader};
3358         use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType};
3359         use bitcoin::blockdata::script::{Builder, Script};
3360         use bitcoin::blockdata::opcodes;
3361         use bitcoin::blockdata::constants::genesis_block;
3362         use bitcoin::network::constants::Network;
3363
3364         use bitcoin_hashes::sha256::Hash as Sha256;
3365         use bitcoin_hashes::Hash;
3366
3367         use hex;
3368
3369         use secp256k1::{Secp256k1, Message};
3370         use secp256k1::key::{PublicKey,SecretKey};
3371
3372         use rand::{thread_rng,Rng};
3373
3374         use std::cell::RefCell;
3375         use std::collections::{BTreeSet, HashMap, HashSet};
3376         use std::default::Default;
3377         use std::rc::Rc;
3378         use std::sync::{Arc, Mutex};
3379         use std::sync::atomic::Ordering;
3380         use std::time::Instant;
3381         use std::mem;
3382
3383         fn build_test_onion_keys() -> Vec<OnionKeys> {
3384                 // Keys from BOLT 4, used in both test vector tests
3385                 let secp_ctx = Secp256k1::new();
3386
3387                 let route = Route {
3388                         hops: vec!(
3389                                         RouteHop {
3390                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
3391                                                 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
3392                                         },
3393                                         RouteHop {
3394                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
3395                                                 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
3396                                         },
3397                                         RouteHop {
3398                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
3399                                                 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
3400                                         },
3401                                         RouteHop {
3402                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..]).unwrap(),
3403                                                 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
3404                                         },
3405                                         RouteHop {
3406                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145").unwrap()[..]).unwrap(),
3407                                                 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
3408                                         },
3409                         ),
3410                 };
3411
3412                 let session_priv = SecretKey::from_slice(&secp_ctx, &hex::decode("4141414141414141414141414141414141414141414141414141414141414141").unwrap()[..]).unwrap();
3413
3414                 let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
3415                 assert_eq!(onion_keys.len(), route.hops.len());
3416                 onion_keys
3417         }
3418
3419         #[test]
3420         fn onion_vectors() {
3421                 // Packet creation test vectors from BOLT 4
3422                 let onion_keys = build_test_onion_keys();
3423
3424                 assert_eq!(onion_keys[0].shared_secret[..], hex::decode("53eb63ea8a3fec3b3cd433b85cd62a4b145e1dda09391b348c4e1cd36a03ea66").unwrap()[..]);
3425                 assert_eq!(onion_keys[0].blinding_factor[..], hex::decode("2ec2e5da605776054187180343287683aa6a51b4b1c04d6dd49c45d8cffb3c36").unwrap()[..]);
3426                 assert_eq!(onion_keys[0].ephemeral_pubkey.serialize()[..], hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]);
3427                 assert_eq!(onion_keys[0].rho, hex::decode("ce496ec94def95aadd4bec15cdb41a740c9f2b62347c4917325fcc6fb0453986").unwrap()[..]);
3428                 assert_eq!(onion_keys[0].mu, hex::decode("b57061dc6d0a2b9f261ac410c8b26d64ac5506cbba30267a649c28c179400eba").unwrap()[..]);
3429
3430                 assert_eq!(onion_keys[1].shared_secret[..], hex::decode("a6519e98832a0b179f62123b3567c106db99ee37bef036e783263602f3488fae").unwrap()[..]);
3431                 assert_eq!(onion_keys[1].blinding_factor[..], hex::decode("bf66c28bc22e598cfd574a1931a2bafbca09163df2261e6d0056b2610dab938f").unwrap()[..]);
3432                 assert_eq!(onion_keys[1].ephemeral_pubkey.serialize()[..], hex::decode("028f9438bfbf7feac2e108d677e3a82da596be706cc1cf342b75c7b7e22bf4e6e2").unwrap()[..]);
3433                 assert_eq!(onion_keys[1].rho, hex::decode("450ffcabc6449094918ebe13d4f03e433d20a3d28a768203337bc40b6e4b2c59").unwrap()[..]);
3434                 assert_eq!(onion_keys[1].mu, hex::decode("05ed2b4a3fb023c2ff5dd6ed4b9b6ea7383f5cfe9d59c11d121ec2c81ca2eea9").unwrap()[..]);
3435
3436                 assert_eq!(onion_keys[2].shared_secret[..], hex::decode("3a6b412548762f0dbccce5c7ae7bb8147d1caf9b5471c34120b30bc9c04891cc").unwrap()[..]);
3437                 assert_eq!(onion_keys[2].blinding_factor[..], hex::decode("a1f2dadd184eb1627049673f18c6325814384facdee5bfd935d9cb031a1698a5").unwrap()[..]);
3438                 assert_eq!(onion_keys[2].ephemeral_pubkey.serialize()[..], hex::decode("03bfd8225241ea71cd0843db7709f4c222f62ff2d4516fd38b39914ab6b83e0da0").unwrap()[..]);
3439                 assert_eq!(onion_keys[2].rho, hex::decode("11bf5c4f960239cb37833936aa3d02cea82c0f39fd35f566109c41f9eac8deea").unwrap()[..]);
3440                 assert_eq!(onion_keys[2].mu, hex::decode("caafe2820fa00eb2eeb78695ae452eba38f5a53ed6d53518c5c6edf76f3f5b78").unwrap()[..]);
3441
3442                 assert_eq!(onion_keys[3].shared_secret[..], hex::decode("21e13c2d7cfe7e18836df50872466117a295783ab8aab0e7ecc8c725503ad02d").unwrap()[..]);
3443                 assert_eq!(onion_keys[3].blinding_factor[..], hex::decode("7cfe0b699f35525029ae0fa437c69d0f20f7ed4e3916133f9cacbb13c82ff262").unwrap()[..]);
3444                 assert_eq!(onion_keys[3].ephemeral_pubkey.serialize()[..], hex::decode("031dde6926381289671300239ea8e57ffaf9bebd05b9a5b95beaf07af05cd43595").unwrap()[..]);
3445                 assert_eq!(onion_keys[3].rho, hex::decode("cbe784ab745c13ff5cffc2fbe3e84424aa0fd669b8ead4ee562901a4a4e89e9e").unwrap()[..]);
3446                 assert_eq!(onion_keys[3].mu, hex::decode("5052aa1b3d9f0655a0932e50d42f0c9ba0705142c25d225515c45f47c0036ee9").unwrap()[..]);
3447
3448                 assert_eq!(onion_keys[4].shared_secret[..], hex::decode("b5756b9b542727dbafc6765a49488b023a725d631af688fc031217e90770c328").unwrap()[..]);
3449                 assert_eq!(onion_keys[4].blinding_factor[..], hex::decode("c96e00dddaf57e7edcd4fb5954be5b65b09f17cb6d20651b4e90315be5779205").unwrap()[..]);
3450                 assert_eq!(onion_keys[4].ephemeral_pubkey.serialize()[..], hex::decode("03a214ebd875aab6ddfd77f22c5e7311d7f77f17a169e599f157bbcdae8bf071f4").unwrap()[..]);
3451                 assert_eq!(onion_keys[4].rho, hex::decode("034e18b8cc718e8af6339106e706c52d8df89e2b1f7e9142d996acf88df8799b").unwrap()[..]);
3452                 assert_eq!(onion_keys[4].mu, hex::decode("8e45e5c61c2b24cb6382444db6698727afb063adecd72aada233d4bf273d975a").unwrap()[..]);
3453
3454                 // Test vectors below are flat-out wrong: they claim to set outgoing_cltv_value to non-0 :/
3455                 let payloads = vec!(
3456                         msgs::OnionHopData {
3457                                 realm: 0,
3458                                 data: msgs::OnionRealm0HopData {
3459                                         short_channel_id: 0,
3460                                         amt_to_forward: 0,
3461                                         outgoing_cltv_value: 0,
3462                                 },
3463                                 hmac: [0; 32],
3464                         },
3465                         msgs::OnionHopData {
3466                                 realm: 0,
3467                                 data: msgs::OnionRealm0HopData {
3468                                         short_channel_id: 0x0101010101010101,
3469                                         amt_to_forward: 0x0100000001,
3470                                         outgoing_cltv_value: 0,
3471                                 },
3472                                 hmac: [0; 32],
3473                         },
3474                         msgs::OnionHopData {
3475                                 realm: 0,
3476                                 data: msgs::OnionRealm0HopData {
3477                                         short_channel_id: 0x0202020202020202,
3478                                         amt_to_forward: 0x0200000002,
3479                                         outgoing_cltv_value: 0,
3480                                 },
3481                                 hmac: [0; 32],
3482                         },
3483                         msgs::OnionHopData {
3484                                 realm: 0,
3485                                 data: msgs::OnionRealm0HopData {
3486                                         short_channel_id: 0x0303030303030303,
3487                                         amt_to_forward: 0x0300000003,
3488                                         outgoing_cltv_value: 0,
3489                                 },
3490                                 hmac: [0; 32],
3491                         },
3492                         msgs::OnionHopData {
3493                                 realm: 0,
3494                                 data: msgs::OnionRealm0HopData {
3495                                         short_channel_id: 0x0404040404040404,
3496                                         amt_to_forward: 0x0400000004,
3497                                         outgoing_cltv_value: 0,
3498                                 },
3499                                 hmac: [0; 32],
3500                         },
3501                 );
3502
3503                 let packet = ChannelManager::construct_onion_packet(payloads, onion_keys, &PaymentHash([0x42; 32]));
3504                 // Just check the final packet encoding, as it includes all the per-hop vectors in it
3505                 // anyway...
3506                 assert_eq!(packet.encode(), hex::decode("0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619e5f14350c2a76fc232b5e46d421e9615471ab9e0bc887beff8c95fdb878f7b3a716a996c7845c93d90e4ecbb9bde4ece2f69425c99e4bc820e44485455f135edc0d10f7d61ab590531cf08000179a333a347f8b4072f216400406bdf3bf038659793d4a1fd7b246979e3150a0a4cb052c9ec69acf0f48c3d39cd55675fe717cb7d80ce721caad69320c3a469a202f1e468c67eaf7a7cd8226d0fd32f7b48084dca885d56047694762b67021713ca673929c163ec36e04e40ca8e1c6d17569419d3039d9a1ec866abe044a9ad635778b961fc0776dc832b3a451bd5d35072d2269cf9b040f6b7a7dad84fb114ed413b1426cb96ceaf83825665ed5a1d002c1687f92465b49ed4c7f0218ff8c6c7dd7221d589c65b3b9aaa71a41484b122846c7c7b57e02e679ea8469b70e14fe4f70fee4d87b910cf144be6fe48eef24da475c0b0bcc6565ae82cd3f4e3b24c76eaa5616c6111343306ab35c1fe5ca4a77c0e314ed7dba39d6f1e0de791719c241a939cc493bea2bae1c1e932679ea94d29084278513c77b899cc98059d06a27d171b0dbdf6bee13ddc4fc17a0c4d2827d488436b57baa167544138ca2e64a11b43ac8a06cd0c2fba2d4d900ed2d9205305e2d7383cc98dacb078133de5f6fb6bed2ef26ba92cea28aafc3b9948dd9ae5559e8bd6920b8cea462aa445ca6a95e0e7ba52961b181c79e73bd581821df2b10173727a810c92b83b5ba4a0403eb710d2ca10689a35bec6c3a708e9e92f7d78ff3c5d9989574b00c6736f84c199256e76e19e78f0c98a9d580b4a658c84fc8f2096c2fbea8f5f8c59d0fdacb3be2802ef802abbecb3aba4acaac69a0e965abd8981e9896b1f6ef9d60f7a164b371af869fd0e48073742825e9434fc54da837e120266d53302954843538ea7c6c3dbfb4ff3b2fdbe244437f2a153ccf7bdb4c92aa08102d4f3cff2ae5ef86fab4653595e6a5837fa2f3e29f27a9cde5966843fb847a4a61f1e76c281fe8bb2b0a181d096100db5a1a5ce7a910238251a43ca556712eaadea167fb4d7d75825e440f3ecd782036d7574df8bceacb397abefc5f5254d2722215c53ff54af8299aaaad642c6d72a14d27882d9bbd539e1cc7a527526ba89b8c037ad09120e98ab042d3e8652b31ae0e478516bfaf88efca9f3676ffe99d2819dcaeb7610a626695f53117665d267d3f7abebd6bbd6733f645c72c389f03855bdf1e4b8075b516569b118233a0f0971d24b83113c0b096f5216a207ca99a7cddc81c130923fe3d91e7508c9ac5f2e914ff5dccab9e558566fa14efb34ac98d878580814b94b73acbfde9072f30b881f7f0fff42d4045d1ace6322d86a97d164aa84d93a60498065cc7c20e636f5862dc81531a88c60305a2e59a985be327a6902e4bed986dbf4a0b50c217af0ea7fdf9ab37f9ea1a1aaa72f54cf40154ea9b269f1a7c09f9f43245109431a175d50e2db0132337baa0ef97eed0fcf20489da36b79a1172faccc2f7ded7c60e00694282d93359c4682135642bc81f433574aa8ef0c97b4ade7ca372c5ffc23c7eddd839bab4e0f14d6df15c9dbeab176bec8b5701cf054eb3072f6dadc98f88819042bf10c407516ee58bce33fbe3b3d86a54255e577db4598e30a135361528c101683a5fcde7e8ba53f3456254be8f45fe3a56120ae96ea3773631fcb3873aa3abd91bcff00bd38bd43697a2e789e00da6077482e7b1b1a677b5afae4c54e6cbdf7377b694eb7d7a5b913476a5be923322d3de06060fd5e819635232a2cf4f0731da13b8546d1d6d4f8d75b9fce6c2341a71b0ea6f780df54bfdb0dd5cd9855179f602f9172307c7268724c3618e6817abd793adc214a0dc0bc616816632f27ea336fb56dfd").unwrap());
3507         }
3508
3509         #[test]
3510         fn test_failure_packet_onion() {
3511                 // Returning Errors test vectors from BOLT 4
3512
3513                 let onion_keys = build_test_onion_keys();
3514                 let onion_error = ChannelManager::build_failure_packet(&onion_keys[4].shared_secret[..], 0x2002, &[0; 0]);
3515                 assert_eq!(onion_error.encode(), hex::decode("4c2fc8bc08510334b6833ad9c3e79cd1b52ae59dfe5c2a4b23ead50f09f7ee0b0002200200fe0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap());
3516
3517                 let onion_packet_1 = ChannelManager::encrypt_failure_packet(&onion_keys[4].shared_secret[..], &onion_error.encode()[..]);
3518                 assert_eq!(onion_packet_1.data, hex::decode("a5e6bd0c74cb347f10cce367f949098f2457d14c046fd8a22cb96efb30b0fdcda8cb9168b50f2fd45edd73c1b0c8b33002df376801ff58aaa94000bf8a86f92620f343baef38a580102395ae3abf9128d1047a0736ff9b83d456740ebbb4aeb3aa9737f18fb4afb4aa074fb26c4d702f42968888550a3bded8c05247e045b866baef0499f079fdaeef6538f31d44deafffdfd3afa2fb4ca9082b8f1c465371a9894dd8c243fb4847e004f5256b3e90e2edde4c9fb3082ddfe4d1e734cacd96ef0706bf63c9984e22dc98851bcccd1c3494351feb458c9c6af41c0044bea3c47552b1d992ae542b17a2d0bba1a096c78d169034ecb55b6e3a7263c26017f033031228833c1daefc0dedb8cf7c3e37c9c37ebfe42f3225c326e8bcfd338804c145b16e34e4").unwrap());
3519
3520                 let onion_packet_2 = ChannelManager::encrypt_failure_packet(&onion_keys[3].shared_secret[..], &onion_packet_1.data[..]);
3521                 assert_eq!(onion_packet_2.data, hex::decode("c49a1ce81680f78f5f2000cda36268de34a3f0a0662f55b4e837c83a8773c22aa081bab1616a0011585323930fa5b9fae0c85770a2279ff59ec427ad1bbff9001c0cd1497004bd2a0f68b50704cf6d6a4bf3c8b6a0833399a24b3456961ba00736785112594f65b6b2d44d9f5ea4e49b5e1ec2af978cbe31c67114440ac51a62081df0ed46d4a3df295da0b0fe25c0115019f03f15ec86fabb4c852f83449e812f141a9395b3f70b766ebbd4ec2fae2b6955bd8f32684c15abfe8fd3a6261e52650e8807a92158d9f1463261a925e4bfba44bd20b166d532f0017185c3a6ac7957adefe45559e3072c8dc35abeba835a8cb01a71a15c736911126f27d46a36168ca5ef7dccd4e2886212602b181463e0dd30185c96348f9743a02aca8ec27c0b90dca270").unwrap());
3522
3523                 let onion_packet_3 = ChannelManager::encrypt_failure_packet(&onion_keys[2].shared_secret[..], &onion_packet_2.data[..]);
3524                 assert_eq!(onion_packet_3.data, hex::decode("a5d3e8634cfe78b2307d87c6d90be6fe7855b4f2cc9b1dfb19e92e4b79103f61ff9ac25f412ddfb7466e74f81b3e545563cdd8f5524dae873de61d7bdfccd496af2584930d2b566b4f8d3881f8c043df92224f38cf094cfc09d92655989531524593ec6d6caec1863bdfaa79229b5020acc034cd6deeea1021c50586947b9b8e6faa83b81fbfa6133c0af5d6b07c017f7158fa94f0d206baf12dda6b68f785b773b360fd0497e16cc402d779c8d48d0fa6315536ef0660f3f4e1865f5b38ea49c7da4fd959de4e83ff3ab686f059a45c65ba2af4a6a79166aa0f496bf04d06987b6d2ea205bdb0d347718b9aeff5b61dfff344993a275b79717cd815b6ad4c0beb568c4ac9c36ff1c315ec1119a1993c4b61e6eaa0375e0aaf738ac691abd3263bf937e3").unwrap());
3525
3526                 let onion_packet_4 = ChannelManager::encrypt_failure_packet(&onion_keys[1].shared_secret[..], &onion_packet_3.data[..]);
3527                 assert_eq!(onion_packet_4.data, hex::decode("aac3200c4968f56b21f53e5e374e3a2383ad2b1b6501bbcc45abc31e59b26881b7dfadbb56ec8dae8857add94e6702fb4c3a4de22e2e669e1ed926b04447fc73034bb730f4932acd62727b75348a648a1128744657ca6a4e713b9b646c3ca66cac02cdab44dd3439890ef3aaf61708714f7375349b8da541b2548d452d84de7084bb95b3ac2345201d624d31f4d52078aa0fa05a88b4e20202bd2b86ac5b52919ea305a8949de95e935eed0319cf3cf19ebea61d76ba92532497fcdc9411d06bcd4275094d0a4a3c5d3a945e43305a5a9256e333e1f64dbca5fcd4e03a39b9012d197506e06f29339dfee3331995b21615337ae060233d39befea925cc262873e0530408e6990f1cbd233a150ef7b004ff6166c70c68d9f8c853c1abca640b8660db2921").unwrap());
3528
3529                 let onion_packet_5 = ChannelManager::encrypt_failure_packet(&onion_keys[0].shared_secret[..], &onion_packet_4.data[..]);
3530                 assert_eq!(onion_packet_5.data, hex::decode("9c5add3963fc7f6ed7f148623c84134b5647e1306419dbe2174e523fa9e2fbed3a06a19f899145610741c83ad40b7712aefaddec8c6baf7325d92ea4ca4d1df8bce517f7e54554608bf2bd8071a4f52a7a2f7ffbb1413edad81eeea5785aa9d990f2865dc23b4bc3c301a94eec4eabebca66be5cf638f693ec256aec514620cc28ee4a94bd9565bc4d4962b9d3641d4278fb319ed2b84de5b665f307a2db0f7fbb757366067d88c50f7e829138fde4f78d39b5b5802f1b92a8a820865af5cc79f9f30bc3f461c66af95d13e5e1f0381c184572a91dee1c849048a647a1158cf884064deddbf1b0b88dfe2f791428d0ba0f6fb2f04e14081f69165ae66d9297c118f0907705c9c4954a199bae0bb96fad763d690e7daa6cfda59ba7f2c8d11448b604d12d").unwrap());
3531         }
3532
3533         fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
3534                 assert!(chain.does_match_tx(tx));
3535                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3536                 chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
3537                 for i in 2..100 {
3538                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3539                         chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
3540                 }
3541         }
3542
3543         struct Node {
3544                 chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
3545                 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
3546                 chan_monitor: Arc<test_utils::TestChannelMonitor>,
3547                 keys_manager: Arc<test_utils::TestKeysInterface>,
3548                 node: Arc<ChannelManager>,
3549                 router: Router,
3550                 node_seed: [u8; 32],
3551                 network_payment_count: Rc<RefCell<u8>>,
3552                 network_chan_count: Rc<RefCell<u32>>,
3553         }
3554         impl Drop for Node {
3555                 fn drop(&mut self) {
3556                         if !::std::thread::panicking() {
3557                                 // Check that we processed all pending events
3558                                 assert_eq!(self.node.get_and_clear_pending_msg_events().len(), 0);
3559                                 assert_eq!(self.node.get_and_clear_pending_events().len(), 0);
3560                                 assert_eq!(self.chan_monitor.added_monitors.lock().unwrap().len(), 0);
3561                         }
3562                 }
3563         }
3564
3565         fn create_chan_between_nodes(node_a: &Node, node_b: &Node) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3566                 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001)
3567         }
3568
3569         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) {
3570                 let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat);
3571                 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
3572                 (announcement, as_update, bs_update, channel_id, tx)
3573         }
3574
3575         macro_rules! get_revoke_commit_msgs {
3576                 ($node: expr, $node_id: expr) => {
3577                         {
3578                                 let events = $node.node.get_and_clear_pending_msg_events();
3579                                 assert_eq!(events.len(), 2);
3580                                 (match events[0] {
3581                                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3582                                                 assert_eq!(*node_id, $node_id);
3583                                                 (*msg).clone()
3584                                         },
3585                                         _ => panic!("Unexpected event"),
3586                                 }, match events[1] {
3587                                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3588                                                 assert_eq!(*node_id, $node_id);
3589                                                 assert!(updates.update_add_htlcs.is_empty());
3590                                                 assert!(updates.update_fulfill_htlcs.is_empty());
3591                                                 assert!(updates.update_fail_htlcs.is_empty());
3592                                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
3593                                                 assert!(updates.update_fee.is_none());
3594                                                 updates.commitment_signed.clone()
3595                                         },
3596                                         _ => panic!("Unexpected event"),
3597                                 })
3598                         }
3599                 }
3600         }
3601
3602         macro_rules! get_event_msg {
3603                 ($node: expr, $event_type: path, $node_id: expr) => {
3604                         {
3605                                 let events = $node.node.get_and_clear_pending_msg_events();
3606                                 assert_eq!(events.len(), 1);
3607                                 match events[0] {
3608                                         $event_type { ref node_id, ref msg } => {
3609                                                 assert_eq!(*node_id, $node_id);
3610                                                 (*msg).clone()
3611                                         },
3612                                         _ => panic!("Unexpected event"),
3613                                 }
3614                         }
3615                 }
3616         }
3617
3618         macro_rules! get_htlc_update_msgs {
3619                 ($node: expr, $node_id: expr) => {
3620                         {
3621                                 let events = $node.node.get_and_clear_pending_msg_events();
3622                                 assert_eq!(events.len(), 1);
3623                                 match events[0] {
3624                                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3625                                                 assert_eq!(*node_id, $node_id);
3626                                                 (*updates).clone()
3627                                         },
3628                                         _ => panic!("Unexpected event"),
3629                                 }
3630                         }
3631                 }
3632         }
3633
3634         macro_rules! get_feerate {
3635                 ($node: expr, $channel_id: expr) => {
3636                         {
3637                                 let chan_lock = $node.node.channel_state.lock().unwrap();
3638                                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
3639                                 chan.get_feerate()
3640                         }
3641                 }
3642         }
3643
3644
3645         fn create_chan_between_nodes_with_value_init(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> Transaction {
3646                 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
3647                 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();
3648                 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();
3649
3650                 let chan_id = *node_a.network_chan_count.borrow();
3651                 let tx;
3652                 let funding_output;
3653
3654                 let events_2 = node_a.node.get_and_clear_pending_events();
3655                 assert_eq!(events_2.len(), 1);
3656                 match events_2[0] {
3657                         Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
3658                                 assert_eq!(*channel_value_satoshis, channel_value);
3659                                 assert_eq!(user_channel_id, 42);
3660
3661                                 tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
3662                                         value: *channel_value_satoshis, script_pubkey: output_script.clone(),
3663                                 }]};
3664                                 funding_output = OutPoint::new(tx.txid(), 0);
3665
3666                                 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
3667                                 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3668                                 assert_eq!(added_monitors.len(), 1);
3669                                 assert_eq!(added_monitors[0].0, funding_output);
3670                                 added_monitors.clear();
3671                         },
3672                         _ => panic!("Unexpected event"),
3673                 }
3674
3675                 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();
3676                 {
3677                         let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
3678                         assert_eq!(added_monitors.len(), 1);
3679                         assert_eq!(added_monitors[0].0, funding_output);
3680                         added_monitors.clear();
3681                 }
3682
3683                 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();
3684                 {
3685                         let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3686                         assert_eq!(added_monitors.len(), 1);
3687                         assert_eq!(added_monitors[0].0, funding_output);
3688                         added_monitors.clear();
3689                 }
3690
3691                 let events_4 = node_a.node.get_and_clear_pending_events();
3692                 assert_eq!(events_4.len(), 1);
3693                 match events_4[0] {
3694                         Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
3695                                 assert_eq!(user_channel_id, 42);
3696                                 assert_eq!(*funding_txo, funding_output);
3697                         },
3698                         _ => panic!("Unexpected event"),
3699                 };
3700
3701                 tx
3702         }
3703
3704         fn create_chan_between_nodes_with_value_confirm(node_a: &Node, node_b: &Node, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
3705                 confirm_transaction(&node_b.chain_monitor, &tx, tx.version);
3706                 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();
3707
3708                 let channel_id;
3709
3710                 confirm_transaction(&node_a.chain_monitor, &tx, tx.version);
3711                 let events_6 = node_a.node.get_and_clear_pending_msg_events();
3712                 assert_eq!(events_6.len(), 2);
3713                 ((match events_6[0] {
3714                         MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3715                                 channel_id = msg.channel_id.clone();
3716                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
3717                                 msg.clone()
3718                         },
3719                         _ => panic!("Unexpected event"),
3720                 }, match events_6[1] {
3721                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3722                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
3723                                 msg.clone()
3724                         },
3725                         _ => panic!("Unexpected event"),
3726                 }), channel_id)
3727         }
3728
3729         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) {
3730                 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat);
3731                 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
3732                 (msgs, chan_id, tx)
3733         }
3734
3735         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) {
3736                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0).unwrap();
3737                 let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
3738                 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1).unwrap();
3739
3740                 let events_7 = node_b.node.get_and_clear_pending_msg_events();
3741                 assert_eq!(events_7.len(), 1);
3742                 let (announcement, bs_update) = match events_7[0] {
3743                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3744                                 (msg, update_msg)
3745                         },
3746                         _ => panic!("Unexpected event"),
3747                 };
3748
3749                 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs).unwrap();
3750                 let events_8 = node_a.node.get_and_clear_pending_msg_events();
3751                 assert_eq!(events_8.len(), 1);
3752                 let as_update = match events_8[0] {
3753                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3754                                 assert!(*announcement == *msg);
3755                                 assert_eq!(update_msg.contents.short_channel_id, announcement.contents.short_channel_id);
3756                                 assert_eq!(update_msg.contents.short_channel_id, bs_update.contents.short_channel_id);
3757                                 update_msg
3758                         },
3759                         _ => panic!("Unexpected event"),
3760                 };
3761
3762                 *node_a.network_chan_count.borrow_mut() += 1;
3763
3764                 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
3765         }
3766
3767         fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3768                 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001)
3769         }
3770
3771         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) {
3772                 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat);
3773                 for node in nodes {
3774                         assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
3775                         node.router.handle_channel_update(&chan_announcement.1).unwrap();
3776                         node.router.handle_channel_update(&chan_announcement.2).unwrap();
3777                 }
3778                 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
3779         }
3780
3781         macro_rules! check_spends {
3782                 ($tx: expr, $spends_tx: expr) => {
3783                         {
3784                                 let mut funding_tx_map = HashMap::new();
3785                                 let spends_tx = $spends_tx;
3786                                 funding_tx_map.insert(spends_tx.txid(), spends_tx);
3787                                 $tx.verify(&funding_tx_map).unwrap();
3788                         }
3789                 }
3790         }
3791
3792         macro_rules! get_closing_signed_broadcast {
3793                 ($node: expr, $dest_pubkey: expr) => {
3794                         {
3795                                 let events = $node.get_and_clear_pending_msg_events();
3796                                 assert!(events.len() == 1 || events.len() == 2);
3797                                 (match events[events.len() - 1] {
3798                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
3799                                                 assert_eq!(msg.contents.flags & 2, 2);
3800                                                 msg.clone()
3801                                         },
3802                                         _ => panic!("Unexpected event"),
3803                                 }, if events.len() == 2 {
3804                                         match events[0] {
3805                                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3806                                                         assert_eq!(*node_id, $dest_pubkey);
3807                                                         Some(msg.clone())
3808                                                 },
3809                                                 _ => panic!("Unexpected event"),
3810                                         }
3811                                 } else { None })
3812                         }
3813                 }
3814         }
3815
3816         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) {
3817                 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) };
3818                 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
3819                 let (tx_a, tx_b);
3820
3821                 node_a.close_channel(channel_id).unwrap();
3822                 node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id())).unwrap();
3823
3824                 let events_1 = node_b.get_and_clear_pending_msg_events();
3825                 assert!(events_1.len() >= 1);
3826                 let shutdown_b = match events_1[0] {
3827                         MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
3828                                 assert_eq!(node_id, &node_a.get_our_node_id());
3829                                 msg.clone()
3830                         },
3831                         _ => panic!("Unexpected event"),
3832                 };
3833
3834                 let closing_signed_b = if !close_inbound_first {
3835                         assert_eq!(events_1.len(), 1);
3836                         None
3837                 } else {
3838                         Some(match events_1[1] {
3839                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3840                                         assert_eq!(node_id, &node_a.get_our_node_id());
3841                                         msg.clone()
3842                                 },
3843                                 _ => panic!("Unexpected event"),
3844                         })
3845                 };
3846
3847                 node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b).unwrap();
3848                 let (as_update, bs_update) = if close_inbound_first {
3849                         assert!(node_a.get_and_clear_pending_msg_events().is_empty());
3850                         node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3851                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3852                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3853                         let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3854
3855                         node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
3856                         let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3857                         assert!(none_b.is_none());
3858                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3859                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3860                         (as_update, bs_update)
3861                 } else {
3862                         let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
3863
3864                         node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a).unwrap();
3865                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3866                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3867                         let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3868
3869                         node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3870                         let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3871                         assert!(none_a.is_none());
3872                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3873                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3874                         (as_update, bs_update)
3875                 };
3876                 assert_eq!(tx_a, tx_b);
3877                 check_spends!(tx_a, funding_tx);
3878
3879                 (as_update, bs_update, tx_a)
3880         }
3881
3882         struct SendEvent {
3883                 node_id: PublicKey,
3884                 msgs: Vec<msgs::UpdateAddHTLC>,
3885                 commitment_msg: msgs::CommitmentSigned,
3886         }
3887         impl SendEvent {
3888                 fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
3889                         assert!(updates.update_fulfill_htlcs.is_empty());
3890                         assert!(updates.update_fail_htlcs.is_empty());
3891                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3892                         assert!(updates.update_fee.is_none());
3893                         SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
3894                 }
3895
3896                 fn from_event(event: MessageSendEvent) -> SendEvent {
3897                         match event {
3898                                 MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
3899                                 _ => panic!("Unexpected event type!"),
3900                         }
3901                 }
3902
3903                 fn from_node(node: &Node) -> SendEvent {
3904                         let mut events = node.node.get_and_clear_pending_msg_events();
3905                         assert_eq!(events.len(), 1);
3906                         SendEvent::from_event(events.pop().unwrap())
3907                 }
3908         }
3909
3910         macro_rules! check_added_monitors {
3911                 ($node: expr, $count: expr) => {
3912                         {
3913                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
3914                                 assert_eq!(added_monitors.len(), $count);
3915                                 added_monitors.clear();
3916                         }
3917                 }
3918         }
3919
3920         macro_rules! commitment_signed_dance {
3921                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
3922                         {
3923                                 check_added_monitors!($node_a, 0);
3924                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3925                                 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3926                                 check_added_monitors!($node_a, 1);
3927                                 commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
3928                         }
3929                 };
3930                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
3931                         {
3932                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
3933                                 check_added_monitors!($node_b, 0);
3934                                 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3935                                 $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
3936                                 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3937                                 check_added_monitors!($node_b, 1);
3938                                 $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed).unwrap();
3939                                 let (bs_revoke_and_ack, extra_msg_option) = {
3940                                         let events = $node_b.node.get_and_clear_pending_msg_events();
3941                                         assert!(events.len() <= 2);
3942                                         (match events[0] {
3943                                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3944                                                         assert_eq!(*node_id, $node_a.node.get_our_node_id());
3945                                                         (*msg).clone()
3946                                                 },
3947                                                 _ => panic!("Unexpected event"),
3948                                         }, events.get(1).map(|e| e.clone()))
3949                                 };
3950                                 check_added_monitors!($node_b, 1);
3951                                 if $fail_backwards {
3952                                         assert!($node_a.node.get_and_clear_pending_events().is_empty());
3953                                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3954                                 }
3955                                 (extra_msg_option, bs_revoke_and_ack)
3956                         }
3957                 };
3958                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
3959                         {
3960                                 check_added_monitors!($node_a, 0);
3961                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3962                                 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3963                                 check_added_monitors!($node_a, 1);
3964                                 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
3965                                 assert!(extra_msg_option.is_none());
3966                                 bs_revoke_and_ack
3967                         }
3968                 };
3969                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
3970                         {
3971                                 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
3972                                 $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
3973                                 {
3974                                         let mut added_monitors = $node_a.chan_monitor.added_monitors.lock().unwrap();
3975                                         if $fail_backwards {
3976                                                 assert_eq!(added_monitors.len(), 2);
3977                                                 assert!(added_monitors[0].0 != added_monitors[1].0);
3978                                         } else {
3979                                                 assert_eq!(added_monitors.len(), 1);
3980                                         }
3981                                         added_monitors.clear();
3982                                 }
3983                                 extra_msg_option
3984                         }
3985                 };
3986                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
3987                         {
3988                                 assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
3989                         }
3990                 };
3991                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
3992                         {
3993                                 commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
3994                                 if $fail_backwards {
3995                                         let channel_state = $node_a.node.channel_state.lock().unwrap();
3996                                         assert_eq!(channel_state.pending_msg_events.len(), 1);
3997                                         if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
3998                                                 assert_ne!(*node_id, $node_b.node.get_our_node_id());
3999                                         } else { panic!("Unexpected event"); }
4000                                 } else {
4001                                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
4002                                 }
4003                         }
4004                 }
4005         }
4006
4007         macro_rules! get_payment_preimage_hash {
4008                 ($node: expr) => {
4009                         {
4010                                 let payment_preimage = PaymentPreimage([*$node.network_payment_count.borrow(); 32]);
4011                                 *$node.network_payment_count.borrow_mut() += 1;
4012                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
4013                                 (payment_preimage, payment_hash)
4014                         }
4015                 }
4016         }
4017
4018         fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
4019                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4020
4021                 let mut payment_event = {
4022                         origin_node.node.send_payment(route, our_payment_hash).unwrap();
4023                         check_added_monitors!(origin_node, 1);
4024
4025                         let mut events = origin_node.node.get_and_clear_pending_msg_events();
4026                         assert_eq!(events.len(), 1);
4027                         SendEvent::from_event(events.remove(0))
4028                 };
4029                 let mut prev_node = origin_node;
4030
4031                 for (idx, &node) in expected_route.iter().enumerate() {
4032                         assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
4033
4034                         node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4035                         check_added_monitors!(node, 0);
4036                         commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
4037
4038                         let events_1 = node.node.get_and_clear_pending_events();
4039                         assert_eq!(events_1.len(), 1);
4040                         match events_1[0] {
4041                                 Event::PendingHTLCsForwardable { .. } => { },
4042                                 _ => panic!("Unexpected event"),
4043                         };
4044
4045                         node.node.channel_state.lock().unwrap().next_forward = Instant::now();
4046                         node.node.process_pending_htlc_forwards();
4047
4048                         if idx == expected_route.len() - 1 {
4049                                 let events_2 = node.node.get_and_clear_pending_events();
4050                                 assert_eq!(events_2.len(), 1);
4051                                 match events_2[0] {
4052                                         Event::PaymentReceived { ref payment_hash, amt } => {
4053                                                 assert_eq!(our_payment_hash, *payment_hash);
4054                                                 assert_eq!(amt, recv_value);
4055                                         },
4056                                         _ => panic!("Unexpected event"),
4057                                 }
4058                         } else {
4059                                 let mut events_2 = node.node.get_and_clear_pending_msg_events();
4060                                 assert_eq!(events_2.len(), 1);
4061                                 check_added_monitors!(node, 1);
4062                                 payment_event = SendEvent::from_event(events_2.remove(0));
4063                                 assert_eq!(payment_event.msgs.len(), 1);
4064                         }
4065
4066                         prev_node = node;
4067                 }
4068
4069                 (our_payment_preimage, our_payment_hash)
4070         }
4071
4072         fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: PaymentPreimage) {
4073                 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
4074                 check_added_monitors!(expected_route.last().unwrap(), 1);
4075
4076                 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
4077                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4078                 macro_rules! get_next_msgs {
4079                         ($node: expr) => {
4080                                 {
4081                                         let events = $node.node.get_and_clear_pending_msg_events();
4082                                         assert_eq!(events.len(), 1);
4083                                         match events[0] {
4084                                                 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 } } => {
4085                                                         assert!(update_add_htlcs.is_empty());
4086                                                         assert_eq!(update_fulfill_htlcs.len(), 1);
4087                                                         assert!(update_fail_htlcs.is_empty());
4088                                                         assert!(update_fail_malformed_htlcs.is_empty());
4089                                                         assert!(update_fee.is_none());
4090                                                         expected_next_node = node_id.clone();
4091                                                         Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()))
4092                                                 },
4093                                                 _ => panic!("Unexpected event"),
4094                                         }
4095                                 }
4096                         }
4097                 }
4098
4099                 macro_rules! last_update_fulfill_dance {
4100                         ($node: expr, $prev_node: expr) => {
4101                                 {
4102                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4103                                         check_added_monitors!($node, 0);
4104                                         assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4105                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4106                                 }
4107                         }
4108                 }
4109                 macro_rules! mid_update_fulfill_dance {
4110                         ($node: expr, $prev_node: expr, $new_msgs: expr) => {
4111                                 {
4112                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4113                                         check_added_monitors!($node, 1);
4114                                         let new_next_msgs = if $new_msgs {
4115                                                 get_next_msgs!($node)
4116                                         } else {
4117                                                 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4118                                                 None
4119                                         };
4120                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4121                                         next_msgs = new_next_msgs;
4122                                 }
4123                         }
4124                 }
4125
4126                 let mut prev_node = expected_route.last().unwrap();
4127                 for (idx, node) in expected_route.iter().rev().enumerate() {
4128                         assert_eq!(expected_next_node, node.node.get_our_node_id());
4129                         let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
4130                         if next_msgs.is_some() {
4131                                 mid_update_fulfill_dance!(node, prev_node, update_next_msgs);
4132                         } else if update_next_msgs {
4133                                 next_msgs = get_next_msgs!(node);
4134                         } else {
4135                                 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
4136                         }
4137                         if !skip_last && idx == expected_route.len() - 1 {
4138                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4139                         }
4140
4141                         prev_node = node;
4142                 }
4143
4144                 if !skip_last {
4145                         last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
4146                         let events = origin_node.node.get_and_clear_pending_events();
4147                         assert_eq!(events.len(), 1);
4148                         match events[0] {
4149                                 Event::PaymentSent { payment_preimage } => {
4150                                         assert_eq!(payment_preimage, our_payment_preimage);
4151                                 },
4152                                 _ => panic!("Unexpected event"),
4153                         }
4154                 }
4155         }
4156
4157         fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: PaymentPreimage) {
4158                 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage);
4159         }
4160
4161         const TEST_FINAL_CLTV: u32 = 32;
4162
4163         fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
4164                 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();
4165                 assert_eq!(route.hops.len(), expected_route.len());
4166                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4167                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
4168                 }
4169
4170                 send_along_route(origin_node, route, expected_route, recv_value)
4171         }
4172
4173         fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
4174                 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();
4175                 assert_eq!(route.hops.len(), expected_route.len());
4176                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4177                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
4178                 }
4179
4180                 let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4181
4182                 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
4183                 match err {
4184                         APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
4185                         _ => panic!("Unknown error variants"),
4186                 };
4187         }
4188
4189         fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
4190                 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
4191                 claim_payment(&origin, expected_route, our_payment_preimage);
4192         }
4193
4194         fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: PaymentHash) {
4195                 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash, 0));
4196                 check_added_monitors!(expected_route.last().unwrap(), 1);
4197
4198                 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
4199                 macro_rules! update_fail_dance {
4200                         ($node: expr, $prev_node: expr, $last_node: expr) => {
4201                                 {
4202                                         $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4203                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
4204                                 }
4205                         }
4206                 }
4207
4208                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4209                 let mut prev_node = expected_route.last().unwrap();
4210                 for (idx, node) in expected_route.iter().rev().enumerate() {
4211                         assert_eq!(expected_next_node, node.node.get_our_node_id());
4212                         if next_msgs.is_some() {
4213                                 // We may be the "last node" for the purpose of the commitment dance if we're
4214                                 // skipping the last node (implying it is disconnected) and we're the
4215                                 // second-to-last node!
4216                                 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
4217                         }
4218
4219                         let events = node.node.get_and_clear_pending_msg_events();
4220                         if !skip_last || idx != expected_route.len() - 1 {
4221                                 assert_eq!(events.len(), 1);
4222                                 match events[0] {
4223                                         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 } } => {
4224                                                 assert!(update_add_htlcs.is_empty());
4225                                                 assert!(update_fulfill_htlcs.is_empty());
4226                                                 assert_eq!(update_fail_htlcs.len(), 1);
4227                                                 assert!(update_fail_malformed_htlcs.is_empty());
4228                                                 assert!(update_fee.is_none());
4229                                                 expected_next_node = node_id.clone();
4230                                                 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
4231                                         },
4232                                         _ => panic!("Unexpected event"),
4233                                 }
4234                         } else {
4235                                 assert!(events.is_empty());
4236                         }
4237                         if !skip_last && idx == expected_route.len() - 1 {
4238                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4239                         }
4240
4241                         prev_node = node;
4242                 }
4243
4244                 if !skip_last {
4245                         update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
4246
4247                         let events = origin_node.node.get_and_clear_pending_events();
4248                         assert_eq!(events.len(), 1);
4249                         match events[0] {
4250                                 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
4251                                         assert_eq!(payment_hash, our_payment_hash);
4252                                         assert!(rejected_by_dest);
4253                                 },
4254                                 _ => panic!("Unexpected event"),
4255                         }
4256                 }
4257         }
4258
4259         fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: PaymentHash) {
4260                 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
4261         }
4262
4263         fn create_network(node_count: usize) -> Vec<Node> {
4264                 let mut nodes = Vec::new();
4265                 let mut rng = thread_rng();
4266                 let secp_ctx = Secp256k1::new();
4267
4268                 let chan_count = Rc::new(RefCell::new(0));
4269                 let payment_count = Rc::new(RefCell::new(0));
4270
4271                 for i in 0..node_count {
4272                         let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
4273                         let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
4274                         let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
4275                         let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
4276                         let mut seed = [0; 32];
4277                         rng.fill_bytes(&mut seed);
4278                         let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&seed, Network::Testnet, Arc::clone(&logger)));
4279                         let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone()));
4280                         let mut config = UserConfig::new();
4281                         config.channel_options.announced_channel = true;
4282                         config.channel_limits.force_announced_channel_preference = false;
4283                         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();
4284                         let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), chain_monitor.clone(), Arc::clone(&logger));
4285                         nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router, keys_manager, node_seed: seed,
4286                                 network_payment_count: payment_count.clone(),
4287                                 network_chan_count: chan_count.clone(),
4288                         });
4289                 }
4290
4291                 nodes
4292         }
4293
4294         #[test]
4295         fn test_async_inbound_update_fee() {
4296                 let mut nodes = create_network(2);
4297                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4298                 let channel_id = chan.2;
4299
4300                 // balancing
4301                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4302
4303                 // A                                        B
4304                 // update_fee                            ->
4305                 // send (1) commitment_signed            -.
4306                 //                                       <- update_add_htlc/commitment_signed
4307                 // send (2) RAA (awaiting remote revoke) -.
4308                 // (1) commitment_signed is delivered    ->
4309                 //                                       .- send (3) RAA (awaiting remote revoke)
4310                 // (2) RAA is delivered                  ->
4311                 //                                       .- send (4) commitment_signed
4312                 //                                       <- (3) RAA is delivered
4313                 // send (5) commitment_signed            -.
4314                 //                                       <- (4) commitment_signed is delivered
4315                 // send (6) RAA                          -.
4316                 // (5) commitment_signed is delivered    ->
4317                 //                                       <- RAA
4318                 // (6) RAA is delivered                  ->
4319
4320                 // First nodes[0] generates an update_fee
4321                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4322                 check_added_monitors!(nodes[0], 1);
4323
4324                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4325                 assert_eq!(events_0.len(), 1);
4326                 let (update_msg, commitment_signed) = match events_0[0] { // (1)
4327                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4328                                 (update_fee.as_ref(), commitment_signed)
4329                         },
4330                         _ => panic!("Unexpected event"),
4331                 };
4332
4333                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4334
4335                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4336                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4337                 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();
4338                 check_added_monitors!(nodes[1], 1);
4339
4340                 let payment_event = {
4341                         let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4342                         assert_eq!(events_1.len(), 1);
4343                         SendEvent::from_event(events_1.remove(0))
4344                 };
4345                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4346                 assert_eq!(payment_event.msgs.len(), 1);
4347
4348                 // ...now when the messages get delivered everyone should be happy
4349                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4350                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4351                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4352                 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4353                 check_added_monitors!(nodes[0], 1);
4354
4355                 // deliver(1), generate (3):
4356                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4357                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4358                 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
4359                 check_added_monitors!(nodes[1], 1);
4360
4361                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap(); // deliver (2)
4362                 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4363                 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
4364                 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
4365                 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
4366                 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
4367                 assert!(bs_update.update_fee.is_none()); // (4)
4368                 check_added_monitors!(nodes[1], 1);
4369
4370                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap(); // deliver (3)
4371                 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4372                 assert!(as_update.update_add_htlcs.is_empty()); // (5)
4373                 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
4374                 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
4375                 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
4376                 assert!(as_update.update_fee.is_none()); // (5)
4377                 check_added_monitors!(nodes[0], 1);
4378
4379                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed).unwrap(); // deliver (4)
4380                 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4381                 // only (6) so get_event_msg's assert(len == 1) passes
4382                 check_added_monitors!(nodes[0], 1);
4383
4384                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed).unwrap(); // deliver (5)
4385                 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4386                 check_added_monitors!(nodes[1], 1);
4387
4388                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4389                 check_added_monitors!(nodes[0], 1);
4390
4391                 let events_2 = nodes[0].node.get_and_clear_pending_events();
4392                 assert_eq!(events_2.len(), 1);
4393                 match events_2[0] {
4394                         Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
4395                         _ => panic!("Unexpected event"),
4396                 }
4397
4398                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap(); // deliver (6)
4399                 check_added_monitors!(nodes[1], 1);
4400         }
4401
4402         #[test]
4403         fn test_update_fee_unordered_raa() {
4404                 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
4405                 // crash in an earlier version of the update_fee patch)
4406                 let mut nodes = create_network(2);
4407                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4408                 let channel_id = chan.2;
4409
4410                 // balancing
4411                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4412
4413                 // First nodes[0] generates an update_fee
4414                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4415                 check_added_monitors!(nodes[0], 1);
4416
4417                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4418                 assert_eq!(events_0.len(), 1);
4419                 let update_msg = match events_0[0] { // (1)
4420                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
4421                                 update_fee.as_ref()
4422                         },
4423                         _ => panic!("Unexpected event"),
4424                 };
4425
4426                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4427
4428                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4429                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4430                 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();
4431                 check_added_monitors!(nodes[1], 1);
4432
4433                 let payment_event = {
4434                         let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4435                         assert_eq!(events_1.len(), 1);
4436                         SendEvent::from_event(events_1.remove(0))
4437                 };
4438                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4439                 assert_eq!(payment_event.msgs.len(), 1);
4440
4441                 // ...now when the messages get delivered everyone should be happy
4442                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4443                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4444                 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4445                 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4446                 check_added_monitors!(nodes[0], 1);
4447
4448                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap(); // deliver (2)
4449                 check_added_monitors!(nodes[1], 1);
4450
4451                 // We can't continue, sadly, because our (1) now has a bogus signature
4452         }
4453
4454         #[test]
4455         fn test_multi_flight_update_fee() {
4456                 let nodes = create_network(2);
4457                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4458                 let channel_id = chan.2;
4459
4460                 // A                                        B
4461                 // update_fee/commitment_signed          ->
4462                 //                                       .- send (1) RAA and (2) commitment_signed
4463                 // update_fee (never committed)          ->
4464                 // (3) update_fee                        ->
4465                 // We have to manually generate the above update_fee, it is allowed by the protocol but we
4466                 // don't track which updates correspond to which revoke_and_ack responses so we're in
4467                 // AwaitingRAA mode and will not generate the update_fee yet.
4468                 //                                       <- (1) RAA delivered
4469                 // (3) is generated and send (4) CS      -.
4470                 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
4471                 // know the per_commitment_point to use for it.
4472                 //                                       <- (2) commitment_signed delivered
4473                 // revoke_and_ack                        ->
4474                 //                                          B should send no response here
4475                 // (4) commitment_signed delivered       ->
4476                 //                                       <- RAA/commitment_signed delivered
4477                 // revoke_and_ack                        ->
4478
4479                 // First nodes[0] generates an update_fee
4480                 let initial_feerate = get_feerate!(nodes[0], channel_id);
4481                 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
4482                 check_added_monitors!(nodes[0], 1);
4483
4484                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4485                 assert_eq!(events_0.len(), 1);
4486                 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
4487                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4488                                 (update_fee.as_ref().unwrap(), commitment_signed)
4489                         },
4490                         _ => panic!("Unexpected event"),
4491                 };
4492
4493                 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
4494                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1).unwrap();
4495                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1).unwrap();
4496                 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4497                 check_added_monitors!(nodes[1], 1);
4498
4499                 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
4500                 // transaction:
4501                 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
4502                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4503                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4504
4505                 // Create the (3) update_fee message that nodes[0] will generate before it does...
4506                 let mut update_msg_2 = msgs::UpdateFee {
4507                         channel_id: update_msg_1.channel_id.clone(),
4508                         feerate_per_kw: (initial_feerate + 30) as u32,
4509                 };
4510
4511                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4512
4513                 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
4514                 // Deliver (3)
4515                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4516
4517                 // Deliver (1), generating (3) and (4)
4518                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap();
4519                 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4520                 check_added_monitors!(nodes[0], 1);
4521                 assert!(as_second_update.update_add_htlcs.is_empty());
4522                 assert!(as_second_update.update_fulfill_htlcs.is_empty());
4523                 assert!(as_second_update.update_fail_htlcs.is_empty());
4524                 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
4525                 // Check that the update_fee newly generated matches what we delivered:
4526                 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
4527                 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
4528
4529                 // Deliver (2) commitment_signed
4530                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
4531                 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4532                 check_added_monitors!(nodes[0], 1);
4533                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4534
4535                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap();
4536                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4537                 check_added_monitors!(nodes[1], 1);
4538
4539                 // Delever (4)
4540                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed).unwrap();
4541                 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4542                 check_added_monitors!(nodes[1], 1);
4543
4544                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4545                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4546                 check_added_monitors!(nodes[0], 1);
4547
4548                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment).unwrap();
4549                 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4550                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4551                 check_added_monitors!(nodes[0], 1);
4552
4553                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap();
4554                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4555                 check_added_monitors!(nodes[1], 1);
4556         }
4557
4558         #[test]
4559         fn test_update_fee_vanilla() {
4560                 let nodes = create_network(2);
4561                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4562                 let channel_id = chan.2;
4563
4564                 let feerate = get_feerate!(nodes[0], channel_id);
4565                 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
4566                 check_added_monitors!(nodes[0], 1);
4567
4568                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4569                 assert_eq!(events_0.len(), 1);
4570                 let (update_msg, commitment_signed) = match events_0[0] {
4571                                 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 } } => {
4572                                 (update_fee.as_ref(), commitment_signed)
4573                         },
4574                         _ => panic!("Unexpected event"),
4575                 };
4576                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4577
4578                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4579                 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4580                 check_added_monitors!(nodes[1], 1);
4581
4582                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4583                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4584                 check_added_monitors!(nodes[0], 1);
4585
4586                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4587                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4588                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4589                 check_added_monitors!(nodes[0], 1);
4590
4591                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4592                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4593                 check_added_monitors!(nodes[1], 1);
4594         }
4595
4596         #[test]
4597         fn test_update_fee_that_funder_cannot_afford() {
4598                 let nodes = create_network(2);
4599                 let channel_value = 1888;
4600                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000);
4601                 let channel_id = chan.2;
4602
4603                 let feerate = 260;
4604                 nodes[0].node.update_fee(channel_id, feerate).unwrap();
4605                 check_added_monitors!(nodes[0], 1);
4606                 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4607
4608                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap()).unwrap();
4609
4610                 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
4611
4612                 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
4613                 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
4614                 {
4615                         let chan_lock = nodes[1].node.channel_state.lock().unwrap();
4616                         let chan = chan_lock.by_id.get(&channel_id).unwrap();
4617
4618                         //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
4619                         let num_htlcs = chan.last_local_commitment_txn[0].output.len() - 2;
4620                         let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
4621                         let mut actual_fee = chan.last_local_commitment_txn[0].output.iter().fold(0, |acc, output| acc + output.value);
4622                         actual_fee = channel_value - actual_fee;
4623                         assert_eq!(total_fee, actual_fee);
4624                 } //drop the mutex
4625
4626                 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
4627                 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
4628                 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
4629                 check_added_monitors!(nodes[0], 1);
4630
4631                 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4632
4633                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap()).unwrap();
4634
4635                 //While producing the commitment_signed response after handling a received update_fee request the
4636                 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
4637                 //Should produce and error.
4638                 let err = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed).unwrap_err();
4639
4640                 assert!(match err.err {
4641                         "Funding remote cannot afford proposed new fee" => true,
4642                         _ => false,
4643                 });
4644
4645                 //clear the message we could not handle
4646                 nodes[1].node.get_and_clear_pending_msg_events();
4647         }
4648
4649         #[test]
4650         fn test_update_fee_with_fundee_update_add_htlc() {
4651                 let mut nodes = create_network(2);
4652                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4653                 let channel_id = chan.2;
4654
4655                 // balancing
4656                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4657
4658                 let feerate = get_feerate!(nodes[0], channel_id);
4659                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4660                 check_added_monitors!(nodes[0], 1);
4661
4662                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4663                 assert_eq!(events_0.len(), 1);
4664                 let (update_msg, commitment_signed) = match events_0[0] {
4665                                 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 } } => {
4666                                 (update_fee.as_ref(), commitment_signed)
4667                         },
4668                         _ => panic!("Unexpected event"),
4669                 };
4670                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4671                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4672                 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4673                 check_added_monitors!(nodes[1], 1);
4674
4675                 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
4676
4677                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
4678
4679                 // nothing happens since node[1] is in AwaitingRemoteRevoke
4680                 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
4681                 {
4682                         let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
4683                         assert_eq!(added_monitors.len(), 0);
4684                         added_monitors.clear();
4685                 }
4686                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4687                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4688                 // node[1] has nothing to do
4689
4690                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4691                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4692                 check_added_monitors!(nodes[0], 1);
4693
4694                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4695                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4696                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4697                 check_added_monitors!(nodes[0], 1);
4698                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4699                 check_added_monitors!(nodes[1], 1);
4700                 // AwaitingRemoteRevoke ends here
4701
4702                 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4703                 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
4704                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
4705                 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
4706                 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
4707                 assert_eq!(commitment_update.update_fee.is_none(), true);
4708
4709                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]).unwrap();
4710                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4711                 check_added_monitors!(nodes[0], 1);
4712                 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4713
4714                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke).unwrap();
4715                 check_added_monitors!(nodes[1], 1);
4716                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4717
4718                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed).unwrap();
4719                 check_added_monitors!(nodes[1], 1);
4720                 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4721                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4722
4723                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke).unwrap();
4724                 check_added_monitors!(nodes[0], 1);
4725                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4726
4727                 let events = nodes[0].node.get_and_clear_pending_events();
4728                 assert_eq!(events.len(), 1);
4729                 match events[0] {
4730                         Event::PendingHTLCsForwardable { .. } => { },
4731                         _ => panic!("Unexpected event"),
4732                 };
4733                 nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
4734                 nodes[0].node.process_pending_htlc_forwards();
4735
4736                 let events = nodes[0].node.get_and_clear_pending_events();
4737                 assert_eq!(events.len(), 1);
4738                 match events[0] {
4739                         Event::PaymentReceived { .. } => { },
4740                         _ => panic!("Unexpected event"),
4741                 };
4742
4743                 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
4744
4745                 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
4746                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
4747                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4748         }
4749
4750         #[test]
4751         fn test_update_fee() {
4752                 let nodes = create_network(2);
4753                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4754                 let channel_id = chan.2;
4755
4756                 // A                                        B
4757                 // (1) update_fee/commitment_signed      ->
4758                 //                                       <- (2) revoke_and_ack
4759                 //                                       .- send (3) commitment_signed
4760                 // (4) update_fee/commitment_signed      ->
4761                 //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
4762                 //                                       <- (3) commitment_signed delivered
4763                 // send (6) revoke_and_ack               -.
4764                 //                                       <- (5) deliver revoke_and_ack
4765                 // (6) deliver revoke_and_ack            ->
4766                 //                                       .- send (7) commitment_signed in response to (4)
4767                 //                                       <- (7) deliver commitment_signed
4768                 // revoke_and_ack                        ->
4769
4770                 // Create and deliver (1)...
4771                 let feerate = get_feerate!(nodes[0], channel_id);
4772                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4773                 check_added_monitors!(nodes[0], 1);
4774
4775                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4776                 assert_eq!(events_0.len(), 1);
4777                 let (update_msg, commitment_signed) = match events_0[0] {
4778                                 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 } } => {
4779                                 (update_fee.as_ref(), commitment_signed)
4780                         },
4781                         _ => panic!("Unexpected event"),
4782                 };
4783                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4784
4785                 // Generate (2) and (3):
4786                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4787                 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4788                 check_added_monitors!(nodes[1], 1);
4789
4790                 // Deliver (2):
4791                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4792                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4793                 check_added_monitors!(nodes[0], 1);
4794
4795                 // Create and deliver (4)...
4796                 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
4797                 check_added_monitors!(nodes[0], 1);
4798                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4799                 assert_eq!(events_0.len(), 1);
4800                 let (update_msg, commitment_signed) = match events_0[0] {
4801                                 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 } } => {
4802                                 (update_fee.as_ref(), commitment_signed)
4803                         },
4804                         _ => panic!("Unexpected event"),
4805                 };
4806
4807                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4808                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4809                 check_added_monitors!(nodes[1], 1);
4810                 // ... creating (5)
4811                 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4812                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4813
4814                 // Handle (3), creating (6):
4815                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0).unwrap();
4816                 check_added_monitors!(nodes[0], 1);
4817                 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4818                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4819
4820                 // Deliver (5):
4821                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4822                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4823                 check_added_monitors!(nodes[0], 1);
4824
4825                 // Deliver (6), creating (7):
4826                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0).unwrap();
4827                 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4828                 assert!(commitment_update.update_add_htlcs.is_empty());
4829                 assert!(commitment_update.update_fulfill_htlcs.is_empty());
4830                 assert!(commitment_update.update_fail_htlcs.is_empty());
4831                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
4832                 assert!(commitment_update.update_fee.is_none());
4833                 check_added_monitors!(nodes[1], 1);
4834
4835                 // Deliver (7)
4836                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4837                 check_added_monitors!(nodes[0], 1);
4838                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4839                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4840
4841                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4842                 check_added_monitors!(nodes[1], 1);
4843                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4844
4845                 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
4846                 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
4847                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4848         }
4849
4850         #[test]
4851         fn pre_funding_lock_shutdown_test() {
4852                 // Test sending a shutdown prior to funding_locked after funding generation
4853                 let nodes = create_network(2);
4854                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0);
4855                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4856                 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4857                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4858
4859                 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
4860                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4861                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4862                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4863                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4864
4865                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4866                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4867                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4868                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4869                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4870                 assert!(node_0_none.is_none());
4871
4872                 assert!(nodes[0].node.list_channels().is_empty());
4873                 assert!(nodes[1].node.list_channels().is_empty());
4874         }
4875
4876         #[test]
4877         fn updates_shutdown_wait() {
4878                 // Test sending a shutdown with outstanding updates pending
4879                 let mut nodes = create_network(3);
4880                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4881                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4882                 let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4883                 let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4884
4885                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
4886
4887                 nodes[0].node.close_channel(&chan_1.2).unwrap();
4888                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4889                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4890                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4891                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4892
4893                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4894                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4895
4896                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4897                 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route_1, payment_hash) {}
4898                 else { panic!("New sends should fail!") };
4899                 if let Err(APIError::ChannelUnavailable {..}) = nodes[1].node.send_payment(route_2, payment_hash) {}
4900                 else { panic!("New sends should fail!") };
4901
4902                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
4903                 check_added_monitors!(nodes[2], 1);
4904                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4905                 assert!(updates.update_add_htlcs.is_empty());
4906                 assert!(updates.update_fail_htlcs.is_empty());
4907                 assert!(updates.update_fail_malformed_htlcs.is_empty());
4908                 assert!(updates.update_fee.is_none());
4909                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4910                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
4911                 check_added_monitors!(nodes[1], 1);
4912                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4913                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
4914
4915                 assert!(updates_2.update_add_htlcs.is_empty());
4916                 assert!(updates_2.update_fail_htlcs.is_empty());
4917                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
4918                 assert!(updates_2.update_fee.is_none());
4919                 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
4920                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
4921                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
4922
4923                 let events = nodes[0].node.get_and_clear_pending_events();
4924                 assert_eq!(events.len(), 1);
4925                 match events[0] {
4926                         Event::PaymentSent { ref payment_preimage } => {
4927                                 assert_eq!(our_payment_preimage, *payment_preimage);
4928                         },
4929                         _ => panic!("Unexpected event"),
4930                 }
4931
4932                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4933                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4934                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4935                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4936                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4937                 assert!(node_0_none.is_none());
4938
4939                 assert!(nodes[0].node.list_channels().is_empty());
4940
4941                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4942                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
4943                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
4944                 assert!(nodes[1].node.list_channels().is_empty());
4945                 assert!(nodes[2].node.list_channels().is_empty());
4946         }
4947
4948         #[test]
4949         fn htlc_fail_async_shutdown() {
4950                 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
4951                 let mut nodes = create_network(3);
4952                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4953                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4954
4955                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4956                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4957                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
4958                 check_added_monitors!(nodes[0], 1);
4959                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4960                 assert_eq!(updates.update_add_htlcs.len(), 1);
4961                 assert!(updates.update_fulfill_htlcs.is_empty());
4962                 assert!(updates.update_fail_htlcs.is_empty());
4963                 assert!(updates.update_fail_malformed_htlcs.is_empty());
4964                 assert!(updates.update_fee.is_none());
4965
4966                 nodes[1].node.close_channel(&chan_1.2).unwrap();
4967                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4968                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4969                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4970
4971                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
4972                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
4973                 check_added_monitors!(nodes[1], 1);
4974                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4975                 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
4976
4977                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4978                 assert!(updates_2.update_add_htlcs.is_empty());
4979                 assert!(updates_2.update_fulfill_htlcs.is_empty());
4980                 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
4981                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
4982                 assert!(updates_2.update_fee.is_none());
4983
4984                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]).unwrap();
4985                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
4986
4987                 let events = nodes[0].node.get_and_clear_pending_events();
4988                 assert_eq!(events.len(), 1);
4989                 match events[0] {
4990                         Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } => {
4991                                 assert_eq!(our_payment_hash, *payment_hash);
4992                                 assert!(!rejected_by_dest);
4993                         },
4994                         _ => panic!("Unexpected event"),
4995                 }
4996
4997                 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4998                 assert_eq!(msg_events.len(), 2);
4999                 let node_0_closing_signed = match msg_events[0] {
5000                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
5001                                 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5002                                 (*msg).clone()
5003                         },
5004                         _ => panic!("Unexpected event"),
5005                 };
5006                 match msg_events[1] {
5007                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
5008                                 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
5009                         },
5010                         _ => panic!("Unexpected event"),
5011                 }
5012
5013                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5014                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5015                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5016                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5017                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5018                 assert!(node_0_none.is_none());
5019
5020                 assert!(nodes[0].node.list_channels().is_empty());
5021
5022                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5023                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5024                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5025                 assert!(nodes[1].node.list_channels().is_empty());
5026                 assert!(nodes[2].node.list_channels().is_empty());
5027         }
5028
5029         fn do_test_shutdown_rebroadcast(recv_count: u8) {
5030                 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
5031                 // messages delivered prior to disconnect
5032                 let nodes = create_network(3);
5033                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5034                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5035
5036                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
5037
5038                 nodes[1].node.close_channel(&chan_1.2).unwrap();
5039                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5040                 if recv_count > 0 {
5041                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
5042                         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5043                         if recv_count > 1 {
5044                                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
5045                         }
5046                 }
5047
5048                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5049                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5050
5051                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5052                 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5053                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5054                 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5055
5056                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish).unwrap();
5057                 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5058                 assert!(node_1_shutdown == node_1_2nd_shutdown);
5059
5060                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish).unwrap();
5061                 let node_0_2nd_shutdown = if recv_count > 0 {
5062                         let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5063                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5064                         node_0_2nd_shutdown
5065                 } else {
5066                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5067                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5068                         get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
5069                 };
5070                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown).unwrap();
5071
5072                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5073                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5074
5075                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
5076                 check_added_monitors!(nodes[2], 1);
5077                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5078                 assert!(updates.update_add_htlcs.is_empty());
5079                 assert!(updates.update_fail_htlcs.is_empty());
5080                 assert!(updates.update_fail_malformed_htlcs.is_empty());
5081                 assert!(updates.update_fee.is_none());
5082                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5083                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
5084                 check_added_monitors!(nodes[1], 1);
5085                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5086                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
5087
5088                 assert!(updates_2.update_add_htlcs.is_empty());
5089                 assert!(updates_2.update_fail_htlcs.is_empty());
5090                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
5091                 assert!(updates_2.update_fee.is_none());
5092                 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
5093                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
5094                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
5095
5096                 let events = nodes[0].node.get_and_clear_pending_events();
5097                 assert_eq!(events.len(), 1);
5098                 match events[0] {
5099                         Event::PaymentSent { ref payment_preimage } => {
5100                                 assert_eq!(our_payment_preimage, *payment_preimage);
5101                         },
5102                         _ => panic!("Unexpected event"),
5103                 }
5104
5105                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5106                 if recv_count > 0 {
5107                         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5108                         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5109                         assert!(node_1_closing_signed.is_some());
5110                 }
5111
5112                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5113                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5114
5115                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5116                 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5117                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5118                 if recv_count == 0 {
5119                         // If all closing_signeds weren't delivered we can just resume where we left off...
5120                         let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5121
5122                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish).unwrap();
5123                         let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5124                         assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
5125
5126                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish).unwrap();
5127                         let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5128                         assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
5129
5130                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown).unwrap();
5131                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5132
5133                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown).unwrap();
5134                         let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5135                         assert!(node_0_closing_signed == node_0_2nd_closing_signed);
5136
5137                         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed).unwrap();
5138                         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5139                         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5140                         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5141                         assert!(node_0_none.is_none());
5142                 } else {
5143                         // If one node, however, received + responded with an identical closing_signed we end
5144                         // up erroring and node[0] will try to broadcast its own latest commitment transaction.
5145                         // There isn't really anything better we can do simply, but in the future we might
5146                         // explore storing a set of recently-closed channels that got disconnected during
5147                         // closing_signed and avoiding broadcasting local commitment txn for some timeout to
5148                         // give our counterparty enough time to (potentially) broadcast a cooperative closing
5149                         // transaction.
5150                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5151
5152                         if let Err(msgs::HandleError{action: Some(msgs::ErrorAction::SendErrorMessage{msg}), ..}) =
5153                                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish) {
5154                                 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
5155                                 let msgs::ErrorMessage {ref channel_id, ..} = msg;
5156                                 assert_eq!(*channel_id, chan_1.2);
5157                         } else { panic!("Needed SendErrorMessage close"); }
5158
5159                         // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
5160                         // checks it, but in this case nodes[0] didn't ever get a chance to receive a
5161                         // closing_signed so we do it ourselves
5162                         let events = nodes[0].node.get_and_clear_pending_msg_events();
5163                         assert_eq!(events.len(), 1);
5164                         match events[0] {
5165                                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5166                                         assert_eq!(msg.contents.flags & 2, 2);
5167                                 },
5168                                 _ => panic!("Unexpected event"),
5169                         }
5170                 }
5171
5172                 assert!(nodes[0].node.list_channels().is_empty());
5173
5174                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5175                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5176                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5177                 assert!(nodes[1].node.list_channels().is_empty());
5178                 assert!(nodes[2].node.list_channels().is_empty());
5179         }
5180
5181         #[test]
5182         fn test_shutdown_rebroadcast() {
5183                 do_test_shutdown_rebroadcast(0);
5184                 do_test_shutdown_rebroadcast(1);
5185                 do_test_shutdown_rebroadcast(2);
5186         }
5187
5188         #[test]
5189         fn fake_network_test() {
5190                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5191                 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
5192                 let nodes = create_network(4);
5193
5194                 // Create some initial channels
5195                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5196                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5197                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5198
5199                 // Rebalance the network a bit by relaying one payment through all the channels...
5200                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5201                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
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
5205                 // Send some more payments
5206                 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
5207                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
5208                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
5209
5210                 // Test failure packets
5211                 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
5212                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
5213
5214                 // Add a new channel that skips 3
5215                 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
5216
5217                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
5218                 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
5219                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5220                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
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
5225                 // Do some rebalance loop payments, simultaneously
5226                 let mut hops = Vec::with_capacity(3);
5227                 hops.push(RouteHop {
5228                         pubkey: nodes[2].node.get_our_node_id(),
5229                         short_channel_id: chan_2.0.contents.short_channel_id,
5230                         fee_msat: 0,
5231                         cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
5232                 });
5233                 hops.push(RouteHop {
5234                         pubkey: nodes[3].node.get_our_node_id(),
5235                         short_channel_id: chan_3.0.contents.short_channel_id,
5236                         fee_msat: 0,
5237                         cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
5238                 });
5239                 hops.push(RouteHop {
5240                         pubkey: nodes[1].node.get_our_node_id(),
5241                         short_channel_id: chan_4.0.contents.short_channel_id,
5242                         fee_msat: 1000000,
5243                         cltv_expiry_delta: TEST_FINAL_CLTV,
5244                 });
5245                 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;
5246                 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;
5247                 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
5248
5249                 let mut hops = Vec::with_capacity(3);
5250                 hops.push(RouteHop {
5251                         pubkey: nodes[3].node.get_our_node_id(),
5252                         short_channel_id: chan_4.0.contents.short_channel_id,
5253                         fee_msat: 0,
5254                         cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
5255                 });
5256                 hops.push(RouteHop {
5257                         pubkey: nodes[2].node.get_our_node_id(),
5258                         short_channel_id: chan_3.0.contents.short_channel_id,
5259                         fee_msat: 0,
5260                         cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
5261                 });
5262                 hops.push(RouteHop {
5263                         pubkey: nodes[1].node.get_our_node_id(),
5264                         short_channel_id: chan_2.0.contents.short_channel_id,
5265                         fee_msat: 1000000,
5266                         cltv_expiry_delta: TEST_FINAL_CLTV,
5267                 });
5268                 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;
5269                 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;
5270                 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
5271
5272                 // Claim the rebalances...
5273                 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
5274                 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
5275
5276                 // Add a duplicate new channel from 2 to 4
5277                 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3);
5278
5279                 // Send some payments across both channels
5280                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5281                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5282                 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5283
5284                 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
5285
5286                 //TODO: Test that routes work again here as we've been notified that the channel is full
5287
5288                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
5289                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
5290                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
5291
5292                 // Close down the channels...
5293                 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
5294                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
5295                 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
5296                 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
5297                 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
5298         }
5299
5300         #[test]
5301         fn duplicate_htlc_test() {
5302                 // Test that we accept duplicate payment_hash HTLCs across the network and that
5303                 // claiming/failing them are all separate and don't effect each other
5304                 let mut nodes = create_network(6);
5305
5306                 // Create some initial channels to route via 3 to 4/5 from 0/1/2
5307                 create_announced_chan_between_nodes(&nodes, 0, 3);
5308                 create_announced_chan_between_nodes(&nodes, 1, 3);
5309                 create_announced_chan_between_nodes(&nodes, 2, 3);
5310                 create_announced_chan_between_nodes(&nodes, 3, 4);
5311                 create_announced_chan_between_nodes(&nodes, 3, 5);
5312
5313                 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
5314
5315                 *nodes[0].network_payment_count.borrow_mut() -= 1;
5316                 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
5317
5318                 *nodes[0].network_payment_count.borrow_mut() -= 1;
5319                 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
5320
5321                 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
5322                 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
5323                 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
5324         }
5325
5326         #[derive(PartialEq)]
5327         enum HTLCType { NONE, TIMEOUT, SUCCESS }
5328         /// Tests that the given node has broadcast transactions for the given Channel
5329         ///
5330         /// First checks that the latest local commitment tx has been broadcast, unless an explicit
5331         /// commitment_tx is provided, which may be used to test that a remote commitment tx was
5332         /// broadcast and the revoked outputs were claimed.
5333         ///
5334         /// Next tests that there is (or is not) a transaction that spends the commitment transaction
5335         /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
5336         ///
5337         /// All broadcast transactions must be accounted for in one of the above three types of we'll
5338         /// also fail.
5339         fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
5340                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5341                 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
5342
5343                 let mut res = Vec::with_capacity(2);
5344                 node_txn.retain(|tx| {
5345                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
5346                                 check_spends!(tx, chan.3.clone());
5347                                 if commitment_tx.is_none() {
5348                                         res.push(tx.clone());
5349                                 }
5350                                 false
5351                         } else { true }
5352                 });
5353                 if let Some(explicit_tx) = commitment_tx {
5354                         res.push(explicit_tx.clone());
5355                 }
5356
5357                 assert_eq!(res.len(), 1);
5358
5359                 if has_htlc_tx != HTLCType::NONE {
5360                         node_txn.retain(|tx| {
5361                                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
5362                                         check_spends!(tx, res[0].clone());
5363                                         if has_htlc_tx == HTLCType::TIMEOUT {
5364                                                 assert!(tx.lock_time != 0);
5365                                         } else {
5366                                                 assert!(tx.lock_time == 0);
5367                                         }
5368                                         res.push(tx.clone());
5369                                         false
5370                                 } else { true }
5371                         });
5372                         assert!(res.len() == 2 || res.len() == 3);
5373                         if res.len() == 3 {
5374                                 assert_eq!(res[1], res[2]);
5375                         }
5376                 }
5377
5378                 assert!(node_txn.is_empty());
5379                 res
5380         }
5381
5382         /// Tests that the given node has broadcast a claim transaction against the provided revoked
5383         /// HTLC transaction.
5384         fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
5385                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5386                 assert_eq!(node_txn.len(), 1);
5387                 node_txn.retain(|tx| {
5388                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
5389                                 check_spends!(tx, revoked_tx.clone());
5390                                 false
5391                         } else { true }
5392                 });
5393                 assert!(node_txn.is_empty());
5394         }
5395
5396         fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
5397                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5398
5399                 assert!(node_txn.len() >= 1);
5400                 assert_eq!(node_txn[0].input.len(), 1);
5401                 let mut found_prev = false;
5402
5403                 for tx in prev_txn {
5404                         if node_txn[0].input[0].previous_output.txid == tx.txid() {
5405                                 check_spends!(node_txn[0], tx.clone());
5406                                 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
5407                                 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
5408
5409                                 found_prev = true;
5410                                 break;
5411                         }
5412                 }
5413                 assert!(found_prev);
5414
5415                 let mut res = Vec::new();
5416                 mem::swap(&mut *node_txn, &mut res);
5417                 res
5418         }
5419
5420         fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
5421                 let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
5422                 assert_eq!(events_1.len(), 1);
5423                 let as_update = match events_1[0] {
5424                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5425                                 msg.clone()
5426                         },
5427                         _ => panic!("Unexpected event"),
5428                 };
5429
5430                 let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
5431                 assert_eq!(events_2.len(), 1);
5432                 let bs_update = match events_2[0] {
5433                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5434                                 msg.clone()
5435                         },
5436                         _ => panic!("Unexpected event"),
5437                 };
5438
5439                 for node in nodes {
5440                         node.router.handle_channel_update(&as_update).unwrap();
5441                         node.router.handle_channel_update(&bs_update).unwrap();
5442                 }
5443         }
5444
5445         macro_rules! expect_pending_htlcs_forwardable {
5446                 ($node: expr) => {{
5447                         let events = $node.node.get_and_clear_pending_events();
5448                         assert_eq!(events.len(), 1);
5449                         match events[0] {
5450                                 Event::PendingHTLCsForwardable { .. } => { },
5451                                 _ => panic!("Unexpected event"),
5452                         };
5453                         $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
5454                         $node.node.process_pending_htlc_forwards();
5455                 }}
5456         }
5457
5458         fn do_channel_reserve_test(test_recv: bool) {
5459                 use util::rng;
5460                 use std::sync::atomic::Ordering;
5461                 use ln::msgs::HandleError;
5462
5463                 macro_rules! get_channel_value_stat {
5464                         ($node: expr, $channel_id: expr) => {{
5465                                 let chan_lock = $node.node.channel_state.lock().unwrap();
5466                                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
5467                                 chan.get_value_stat()
5468                         }}
5469                 }
5470
5471                 let mut nodes = create_network(3);
5472                 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001);
5473                 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001);
5474
5475                 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
5476                 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
5477
5478                 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
5479                 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
5480
5481                 macro_rules! get_route_and_payment_hash {
5482                         ($recv_value: expr) => {{
5483                                 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
5484                                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5485                                 (route, payment_hash, payment_preimage)
5486                         }}
5487                 };
5488
5489                 macro_rules! expect_forward {
5490                         ($node: expr) => {{
5491                                 let mut events = $node.node.get_and_clear_pending_msg_events();
5492                                 assert_eq!(events.len(), 1);
5493                                 check_added_monitors!($node, 1);
5494                                 let payment_event = SendEvent::from_event(events.remove(0));
5495                                 payment_event
5496                         }}
5497                 }
5498
5499                 macro_rules! expect_payment_received {
5500                         ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
5501                                 let events = $node.node.get_and_clear_pending_events();
5502                                 assert_eq!(events.len(), 1);
5503                                 match events[0] {
5504                                         Event::PaymentReceived { ref payment_hash, amt } => {
5505                                                 assert_eq!($expected_payment_hash, *payment_hash);
5506                                                 assert_eq!($expected_recv_value, amt);
5507                                         },
5508                                         _ => panic!("Unexpected event"),
5509                                 }
5510                         }
5511                 };
5512
5513                 let feemsat = 239; // somehow we know?
5514                 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
5515
5516                 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
5517
5518                 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
5519                 {
5520                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
5521                         assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
5522                         let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
5523                         match err {
5524                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
5525                                 _ => panic!("Unknown error variants"),
5526                         }
5527                 }
5528
5529                 let mut htlc_id = 0;
5530                 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
5531                 // nodes[0]'s wealth
5532                 loop {
5533                         let amt_msat = recv_value_0 + total_fee_msat;
5534                         if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
5535                                 break;
5536                         }
5537                         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
5538                         htlc_id += 1;
5539
5540                         let (stat01_, stat11_, stat12_, stat22_) = (
5541                                 get_channel_value_stat!(nodes[0], chan_1.2),
5542                                 get_channel_value_stat!(nodes[1], chan_1.2),
5543                                 get_channel_value_stat!(nodes[1], chan_2.2),
5544                                 get_channel_value_stat!(nodes[2], chan_2.2),
5545                         );
5546
5547                         assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
5548                         assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
5549                         assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
5550                         assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
5551                         stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
5552                 }
5553
5554                 {
5555                         let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
5556                         // attempt to get channel_reserve violation
5557                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
5558                         let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
5559                         match err {
5560                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5561                                 _ => panic!("Unknown error variants"),
5562                         }
5563                 }
5564
5565                 // adding pending output
5566                 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
5567                 let amt_msat_1 = recv_value_1 + total_fee_msat;
5568
5569                 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
5570                 let payment_event_1 = {
5571                         nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
5572                         check_added_monitors!(nodes[0], 1);
5573
5574                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5575                         assert_eq!(events.len(), 1);
5576                         SendEvent::from_event(events.remove(0))
5577                 };
5578                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]).unwrap();
5579
5580                 // channel reserve test with htlc pending output > 0
5581                 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
5582                 {
5583                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5584                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5585                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5586                                 _ => panic!("Unknown error variants"),
5587                         }
5588                 }
5589
5590                 {
5591                         // test channel_reserve test on nodes[1] side
5592                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5593
5594                         // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
5595                         let secp_ctx = Secp256k1::new();
5596                         let session_priv = SecretKey::from_slice(&secp_ctx, &{
5597                                 let mut session_key = [0; 32];
5598                                 rng::fill_bytes(&mut session_key);
5599                                 session_key
5600                         }).expect("RNG is bad!");
5601
5602                         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5603                         let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
5604                         let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height).unwrap();
5605                         let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
5606                         let msg = msgs::UpdateAddHTLC {
5607                                 channel_id: chan_1.2,
5608                                 htlc_id,
5609                                 amount_msat: htlc_msat,
5610                                 payment_hash: our_payment_hash,
5611                                 cltv_expiry: htlc_cltv,
5612                                 onion_routing_packet: onion_packet,
5613                         };
5614
5615                         if test_recv {
5616                                 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).err().unwrap();
5617                                 match err {
5618                                         HandleError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
5619                                 }
5620                                 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
5621                                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5622                                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5623                                 let channel_close_broadcast = nodes[1].node.get_and_clear_pending_msg_events();
5624                                 assert_eq!(channel_close_broadcast.len(), 1);
5625                                 match channel_close_broadcast[0] {
5626                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5627                                                 assert_eq!(msg.contents.flags & 2, 2);
5628                                         },
5629                                         _ => panic!("Unexpected event"),
5630                                 }
5631                                 return;
5632                         }
5633                 }
5634
5635                 // split the rest to test holding cell
5636                 let recv_value_21 = recv_value_2/2;
5637                 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
5638                 {
5639                         let stat = get_channel_value_stat!(nodes[0], chan_1.2);
5640                         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);
5641                 }
5642
5643                 // now see if they go through on both sides
5644                 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
5645                 // but this will stuck in the holding cell
5646                 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
5647                 check_added_monitors!(nodes[0], 0);
5648                 let events = nodes[0].node.get_and_clear_pending_events();
5649                 assert_eq!(events.len(), 0);
5650
5651                 // test with outbound holding cell amount > 0
5652                 {
5653                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
5654                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5655                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5656                                 _ => panic!("Unknown error variants"),
5657                         }
5658                 }
5659
5660                 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
5661                 // this will also stuck in the holding cell
5662                 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
5663                 check_added_monitors!(nodes[0], 0);
5664                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
5665                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5666
5667                 // flush the pending htlc
5668                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg).unwrap();
5669                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5670                 check_added_monitors!(nodes[1], 1);
5671
5672                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
5673                 check_added_monitors!(nodes[0], 1);
5674                 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5675
5676                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed).unwrap();
5677                 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
5678                 // No commitment_signed so get_event_msg's assert(len == 1) passes
5679                 check_added_monitors!(nodes[0], 1);
5680
5681                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
5682                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5683                 check_added_monitors!(nodes[1], 1);
5684
5685                 expect_pending_htlcs_forwardable!(nodes[1]);
5686
5687                 let ref payment_event_11 = expect_forward!(nodes[1]);
5688                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]).unwrap();
5689                 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
5690
5691                 expect_pending_htlcs_forwardable!(nodes[2]);
5692                 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
5693
5694                 // flush the htlcs in the holding cell
5695                 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
5696                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]).unwrap();
5697                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]).unwrap();
5698                 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
5699                 expect_pending_htlcs_forwardable!(nodes[1]);
5700
5701                 let ref payment_event_3 = expect_forward!(nodes[1]);
5702                 assert_eq!(payment_event_3.msgs.len(), 2);
5703                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]).unwrap();
5704                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]).unwrap();
5705
5706                 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
5707                 expect_pending_htlcs_forwardable!(nodes[2]);
5708
5709                 let events = nodes[2].node.get_and_clear_pending_events();
5710                 assert_eq!(events.len(), 2);
5711                 match events[0] {
5712                         Event::PaymentReceived { ref payment_hash, amt } => {
5713                                 assert_eq!(our_payment_hash_21, *payment_hash);
5714                                 assert_eq!(recv_value_21, amt);
5715                         },
5716                         _ => panic!("Unexpected event"),
5717                 }
5718                 match events[1] {
5719                         Event::PaymentReceived { ref payment_hash, amt } => {
5720                                 assert_eq!(our_payment_hash_22, *payment_hash);
5721                                 assert_eq!(recv_value_22, amt);
5722                         },
5723                         _ => panic!("Unexpected event"),
5724                 }
5725
5726                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
5727                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
5728                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
5729
5730                 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);
5731                 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
5732                 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
5733                 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
5734
5735                 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
5736                 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
5737         }
5738
5739         #[test]
5740         fn channel_reserve_test() {
5741                 do_channel_reserve_test(false);
5742                 do_channel_reserve_test(true);
5743         }
5744
5745         #[test]
5746         fn channel_monitor_network_test() {
5747                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5748                 // tests that ChannelMonitor is able to recover from various states.
5749                 let nodes = create_network(5);
5750
5751                 // Create some initial channels
5752                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5753                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5754                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5755                 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5756
5757                 // Rebalance the network a bit by relaying one payment through all the channels...
5758                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5759                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
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
5763                 // Simple case with no pending HTLCs:
5764                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
5765                 {
5766                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
5767                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5768                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5769                         test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
5770                 }
5771                 get_announce_close_broadcast_events(&nodes, 0, 1);
5772                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5773                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5774
5775                 // One pending HTLC is discarded by the force-close:
5776                 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
5777
5778                 // Simple case of one pending HTLC to HTLC-Timeout
5779                 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
5780                 {
5781                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
5782                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5783                         nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5784                         test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
5785                 }
5786                 get_announce_close_broadcast_events(&nodes, 1, 2);
5787                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5788                 assert_eq!(nodes[2].node.list_channels().len(), 1);
5789
5790                 macro_rules! claim_funds {
5791                         ($node: expr, $prev_node: expr, $preimage: expr) => {
5792                                 {
5793                                         assert!($node.node.claim_funds($preimage));
5794                                         check_added_monitors!($node, 1);
5795
5796                                         let events = $node.node.get_and_clear_pending_msg_events();
5797                                         assert_eq!(events.len(), 1);
5798                                         match events[0] {
5799                                                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
5800                                                         assert!(update_add_htlcs.is_empty());
5801                                                         assert!(update_fail_htlcs.is_empty());
5802                                                         assert_eq!(*node_id, $prev_node.node.get_our_node_id());
5803                                                 },
5804                                                 _ => panic!("Unexpected event"),
5805                                         };
5806                                 }
5807                         }
5808                 }
5809
5810                 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
5811                 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
5812                 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
5813                 {
5814                         let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
5815
5816                         // Claim the payment on nodes[3], giving it knowledge of the preimage
5817                         claim_funds!(nodes[3], nodes[2], payment_preimage_1);
5818
5819                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5820                         nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
5821
5822                         check_preimage_claim(&nodes[3], &node_txn);
5823                 }
5824                 get_announce_close_broadcast_events(&nodes, 2, 3);
5825                 assert_eq!(nodes[2].node.list_channels().len(), 0);
5826                 assert_eq!(nodes[3].node.list_channels().len(), 1);
5827
5828                 { // Cheat and reset nodes[4]'s height to 1
5829                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5830                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![] }, 1);
5831                 }
5832
5833                 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
5834                 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
5835                 // One pending HTLC to time out:
5836                 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
5837                 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
5838                 // buffer space).
5839
5840                 {
5841                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5842                         nodes[3].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5843                         for i in 3..TEST_FINAL_CLTV + 2 + HTLC_FAIL_TIMEOUT_BLOCKS + 1 {
5844                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5845                                 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5846                         }
5847
5848                         let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
5849
5850                         // Claim the payment on nodes[4], giving it knowledge of the preimage
5851                         claim_funds!(nodes[4], nodes[3], payment_preimage_2);
5852
5853                         header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5854                         nodes[4].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5855                         for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
5856                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5857                                 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5858                         }
5859
5860                         test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
5861
5862                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5863                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
5864
5865                         check_preimage_claim(&nodes[4], &node_txn);
5866                 }
5867                 get_announce_close_broadcast_events(&nodes, 3, 4);
5868                 assert_eq!(nodes[3].node.list_channels().len(), 0);
5869                 assert_eq!(nodes[4].node.list_channels().len(), 0);
5870         }
5871
5872         #[test]
5873         fn test_justice_tx() {
5874                 // Test justice txn built on revoked HTLC-Success tx, against both sides
5875
5876                 let nodes = create_network(2);
5877                 // Create some new channels:
5878                 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
5879
5880                 // A pending HTLC which will be revoked:
5881                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5882                 // Get the will-be-revoked local txn from nodes[0]
5883                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5884                 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
5885                 assert_eq!(revoked_local_txn[0].input.len(), 1);
5886                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
5887                 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
5888                 assert_eq!(revoked_local_txn[1].input.len(), 1);
5889                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
5890                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
5891                 // Revoke the old state
5892                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
5893
5894                 {
5895                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5896                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5897                         {
5898                                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5899                                 assert_eq!(node_txn.len(), 3);
5900                                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5901                                 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
5902
5903                                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5904                                 node_txn.swap_remove(0);
5905                         }
5906                         test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
5907
5908                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5909                         let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
5910                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5911                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5912                         test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
5913                 }
5914                 get_announce_close_broadcast_events(&nodes, 0, 1);
5915
5916                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5917                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5918
5919                 // We test justice_tx build by A on B's revoked HTLC-Success tx
5920                 // Create some new channels:
5921                 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
5922
5923                 // A pending HTLC which will be revoked:
5924                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5925                 // Get the will-be-revoked local txn from B
5926                 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5927                 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
5928                 assert_eq!(revoked_local_txn[0].input.len(), 1);
5929                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
5930                 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
5931                 // Revoke the old state
5932                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
5933                 {
5934                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5935                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5936                         {
5937                                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5938                                 assert_eq!(node_txn.len(), 3);
5939                                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5940                                 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
5941
5942                                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5943                                 node_txn.swap_remove(0);
5944                         }
5945                         test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
5946
5947                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5948                         let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
5949                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5950                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5951                         test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone());
5952                 }
5953                 get_announce_close_broadcast_events(&nodes, 0, 1);
5954                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5955                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5956         }
5957
5958         #[test]
5959         fn revoked_output_claim() {
5960                 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
5961                 // transaction is broadcast by its counterparty
5962                 let nodes = create_network(2);
5963                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5964                 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
5965                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5966                 assert_eq!(revoked_local_txn.len(), 1);
5967                 // Only output is the full channel value back to nodes[0]:
5968                 assert_eq!(revoked_local_txn[0].output.len(), 1);
5969                 // Send a payment through, updating everyone's latest commitment txn
5970                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
5971
5972                 // Inform nodes[1] that nodes[0] broadcast a stale tx
5973                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5974                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5975                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5976                 assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
5977
5978                 assert_eq!(node_txn[0], node_txn[2]);
5979
5980                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5981                 check_spends!(node_txn[1], chan_1.3.clone());
5982
5983                 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
5984                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5985                 get_announce_close_broadcast_events(&nodes, 0, 1);
5986         }
5987
5988         #[test]
5989         fn claim_htlc_outputs_shared_tx() {
5990                 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
5991                 let nodes = create_network(2);
5992
5993                 // Create some new channel:
5994                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5995
5996                 // Rebalance the network to generate htlc in the two directions
5997                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5998                 // 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
5999                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6000                 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6001
6002                 // Get the will-be-revoked local txn from node[0]
6003                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6004                 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
6005                 assert_eq!(revoked_local_txn[0].input.len(), 1);
6006                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
6007                 assert_eq!(revoked_local_txn[1].input.len(), 1);
6008                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
6009                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
6010                 check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
6011
6012                 //Revoke the old state
6013                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6014
6015                 {
6016                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6017                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6018                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6019
6020                         let events = nodes[1].node.get_and_clear_pending_events();
6021                         assert_eq!(events.len(), 1);
6022                         match events[0] {
6023                                 Event::PaymentFailed { payment_hash, .. } => {
6024                                         assert_eq!(payment_hash, payment_hash_2);
6025                                 },
6026                                 _ => panic!("Unexpected event"),
6027                         }
6028
6029                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6030                         assert_eq!(node_txn.len(), 4);
6031
6032                         assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
6033                         check_spends!(node_txn[0], revoked_local_txn[0].clone());
6034
6035                         assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
6036
6037                         let mut witness_lens = BTreeSet::new();
6038                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6039                         witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
6040                         witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
6041                         assert_eq!(witness_lens.len(), 3);
6042                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6043                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
6044                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
6045
6046                         // Next nodes[1] broadcasts its current local tx state:
6047                         assert_eq!(node_txn[1].input.len(), 1);
6048                         assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
6049
6050                         assert_eq!(node_txn[2].input.len(), 1);
6051                         let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
6052                         assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
6053                         assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
6054                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6055                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
6056                 }
6057                 get_announce_close_broadcast_events(&nodes, 0, 1);
6058                 assert_eq!(nodes[0].node.list_channels().len(), 0);
6059                 assert_eq!(nodes[1].node.list_channels().len(), 0);
6060         }
6061
6062         #[test]
6063         fn claim_htlc_outputs_single_tx() {
6064                 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
6065                 let nodes = create_network(2);
6066
6067                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6068
6069                 // Rebalance the network to generate htlc in the two directions
6070                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6071                 // 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
6072                 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
6073                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6074                 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6075
6076                 // Get the will-be-revoked local txn from node[0]
6077                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6078
6079                 //Revoke the old state
6080                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6081
6082                 {
6083                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6084                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6085                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6086
6087                         let events = nodes[1].node.get_and_clear_pending_events();
6088                         assert_eq!(events.len(), 1);
6089                         match events[0] {
6090                                 Event::PaymentFailed { payment_hash, .. } => {
6091                                         assert_eq!(payment_hash, payment_hash_2);
6092                                 },
6093                                 _ => panic!("Unexpected event"),
6094                         }
6095
6096                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6097                         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)
6098
6099                         assert_eq!(node_txn[0], node_txn[7]);
6100                         assert_eq!(node_txn[1], node_txn[8]);
6101                         assert_eq!(node_txn[2], node_txn[9]);
6102                         assert_eq!(node_txn[3], node_txn[10]);
6103                         assert_eq!(node_txn[4], node_txn[11]);
6104                         assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcated by ChannelManger
6105                         assert_eq!(node_txn[4], node_txn[6]);
6106
6107                         assert_eq!(node_txn[0].input.len(), 1);
6108                         assert_eq!(node_txn[1].input.len(), 1);
6109                         assert_eq!(node_txn[2].input.len(), 1);
6110
6111                         let mut revoked_tx_map = HashMap::new();
6112                         revoked_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
6113                         node_txn[0].verify(&revoked_tx_map).unwrap();
6114                         node_txn[1].verify(&revoked_tx_map).unwrap();
6115                         node_txn[2].verify(&revoked_tx_map).unwrap();
6116
6117                         let mut witness_lens = BTreeSet::new();
6118                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6119                         witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
6120                         witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
6121                         assert_eq!(witness_lens.len(), 3);
6122                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6123                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
6124                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
6125
6126                         assert_eq!(node_txn[3].input.len(), 1);
6127                         check_spends!(node_txn[3], chan_1.3.clone());
6128
6129                         assert_eq!(node_txn[4].input.len(), 1);
6130                         let witness_script = node_txn[4].input[0].witness.last().unwrap();
6131                         assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
6132                         assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
6133                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6134                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
6135                 }
6136                 get_announce_close_broadcast_events(&nodes, 0, 1);
6137                 assert_eq!(nodes[0].node.list_channels().len(), 0);
6138                 assert_eq!(nodes[1].node.list_channels().len(), 0);
6139         }
6140
6141         #[test]
6142         fn test_htlc_on_chain_success() {
6143                 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
6144                 // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
6145                 // broadcasting the right event to other nodes in payment path.
6146                 // A --------------------> B ----------------------> C (preimage)
6147                 // First, C should claim the HTLC output via HTLC-Success when its own latest local
6148                 // commitment transaction was broadcast.
6149                 // Then, B should learn the preimage from said transactions, attempting to claim backwards
6150                 // towards B.
6151                 // B should be able to claim via preimage if A then broadcasts its local tx.
6152                 // Finally, when A sees B's latest local commitment transaction it should be able to claim
6153                 // the HTLC output via the preimage it learned (which, once confirmed should generate a
6154                 // PaymentSent event).
6155
6156                 let nodes = create_network(3);
6157
6158                 // Create some initial channels
6159                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6160                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6161
6162                 // Rebalance the network a bit by relaying one payment through all the channels...
6163                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6164                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6165
6166                 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
6167                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6168
6169                 // Broadcast legit commitment tx from C on B's chain
6170                 // Broadcast HTLC Success transation by C on received output from C's commitment tx on B's chain
6171                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6172                 assert_eq!(commitment_tx.len(), 1);
6173                 check_spends!(commitment_tx[0], chan_2.3.clone());
6174                 nodes[2].node.claim_funds(our_payment_preimage);
6175                 check_added_monitors!(nodes[2], 1);
6176                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6177                 assert!(updates.update_add_htlcs.is_empty());
6178                 assert!(updates.update_fail_htlcs.is_empty());
6179                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6180                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
6181
6182                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6183                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6184                 assert_eq!(events.len(), 1);
6185                 match events[0] {
6186                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6187                         _ => panic!("Unexpected event"),
6188                 }
6189                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
6190                 assert_eq!(node_txn.len(), 3);
6191                 assert_eq!(node_txn[1], commitment_tx[0]);
6192                 assert_eq!(node_txn[0], node_txn[2]);
6193                 check_spends!(node_txn[0], commitment_tx[0].clone());
6194                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6195                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6196                 assert_eq!(node_txn[0].lock_time, 0);
6197
6198                 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
6199                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: node_txn}, 1);
6200                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6201                 {
6202                         let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
6203                         assert_eq!(added_monitors.len(), 1);
6204                         assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
6205                         added_monitors.clear();
6206                 }
6207                 assert_eq!(events.len(), 2);
6208                 match events[0] {
6209                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6210                         _ => panic!("Unexpected event"),
6211                 }
6212                 match events[1] {
6213                         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, .. } } => {
6214                                 assert!(update_add_htlcs.is_empty());
6215                                 assert!(update_fail_htlcs.is_empty());
6216                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6217                                 assert!(update_fail_malformed_htlcs.is_empty());
6218                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6219                         },
6220                         _ => panic!("Unexpected event"),
6221                 };
6222                 {
6223                         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
6224                         // commitment transaction with a corresponding HTLC-Timeout transaction, as well as a
6225                         // timeout-claim of the output that nodes[2] just claimed via success.
6226                         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)
6227                         assert_eq!(node_txn.len(), 4);
6228                         assert_eq!(node_txn[0], node_txn[3]);
6229                         check_spends!(node_txn[0], commitment_tx[0].clone());
6230                         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6231                         assert_ne!(node_txn[0].lock_time, 0);
6232                         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
6233                         check_spends!(node_txn[1], chan_2.3.clone());
6234                         check_spends!(node_txn[2], node_txn[1].clone());
6235                         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6236                         assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6237                         assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6238                         assert_ne!(node_txn[2].lock_time, 0);
6239                         node_txn.clear();
6240                 }
6241
6242                 // Broadcast legit commitment tx from A on B's chain
6243                 // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
6244                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6245                 check_spends!(commitment_tx[0], chan_1.3.clone());
6246                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6247                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6248                 assert_eq!(events.len(), 1);
6249                 match events[0] {
6250                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6251                         _ => panic!("Unexpected event"),
6252                 }
6253                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 1 (HTLC-Success) * 2 (block-rescan)
6254                 assert_eq!(node_txn.len(), 3);
6255                 assert_eq!(node_txn[0], node_txn[2]);
6256                 check_spends!(node_txn[0], commitment_tx[0].clone());
6257                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6258                 assert_eq!(node_txn[0].lock_time, 0);
6259                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
6260                 check_spends!(node_txn[1], chan_1.3.clone());
6261                 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6262                 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
6263                 // we already checked the same situation with A.
6264
6265                 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
6266                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
6267                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6268                 assert_eq!(events.len(), 1);
6269                 match events[0] {
6270                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6271                         _ => panic!("Unexpected event"),
6272                 }
6273                 let events = nodes[0].node.get_and_clear_pending_events();
6274                 assert_eq!(events.len(), 1);
6275                 match events[0] {
6276                         Event::PaymentSent { payment_preimage } => {
6277                                 assert_eq!(payment_preimage, our_payment_preimage);
6278                         },
6279                         _ => panic!("Unexpected event"),
6280                 }
6281                 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)
6282                 assert_eq!(node_txn.len(), 4);
6283                 assert_eq!(node_txn[0], node_txn[3]);
6284                 check_spends!(node_txn[0], commitment_tx[0].clone());
6285                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6286                 assert_ne!(node_txn[0].lock_time, 0);
6287                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6288                 check_spends!(node_txn[1], chan_1.3.clone());
6289                 check_spends!(node_txn[2], node_txn[1].clone());
6290                 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6291                 assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6292                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6293                 assert_ne!(node_txn[2].lock_time, 0);
6294         }
6295
6296         #[test]
6297         fn test_htlc_on_chain_timeout() {
6298                 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
6299                 // ChainWatchInterface and timeout the HTLC  bacward accordingly. So here we test that ChannelManager is
6300                 // broadcasting the right event to other nodes in payment path.
6301                 // A ------------------> B ----------------------> C (timeout)
6302                 //    B's commitment tx                 C's commitment tx
6303                 //            \                                  \
6304                 //         B's HTLC timeout tx               B's timeout tx
6305
6306                 let nodes = create_network(3);
6307
6308                 // Create some intial channels
6309                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6310                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6311
6312                 // Rebalance the network a bit by relaying one payment thorugh all the channels...
6313                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6314                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6315
6316                 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
6317                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6318
6319                 // Brodacast legit commitment tx from C on B's chain
6320                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6321                 check_spends!(commitment_tx[0], chan_2.3.clone());
6322                 nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
6323                 {
6324                         let mut added_monitors = nodes[2].chan_monitor.added_monitors.lock().unwrap();
6325                         assert_eq!(added_monitors.len(), 1);
6326                         added_monitors.clear();
6327                 }
6328                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6329                 assert_eq!(events.len(), 1);
6330                 match events[0] {
6331                         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, .. } } => {
6332                                 assert!(update_add_htlcs.is_empty());
6333                                 assert!(!update_fail_htlcs.is_empty());
6334                                 assert!(update_fulfill_htlcs.is_empty());
6335                                 assert!(update_fail_malformed_htlcs.is_empty());
6336                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
6337                         },
6338                         _ => panic!("Unexpected event"),
6339                 };
6340                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6341                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6342                 assert_eq!(events.len(), 1);
6343                 match events[0] {
6344                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6345                         _ => panic!("Unexpected event"),
6346                 }
6347                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
6348                 assert_eq!(node_txn.len(), 1);
6349                 check_spends!(node_txn[0], chan_2.3.clone());
6350                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
6351
6352                 // Broadcast timeout transaction by B on received output fron C's commitment tx on B's chain
6353                 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
6354                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6355                 let timeout_tx;
6356                 {
6357                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6358                         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)
6359                         assert_eq!(node_txn[0], node_txn[5]);
6360                         assert_eq!(node_txn[1], node_txn[6]);
6361                         assert_eq!(node_txn[2], node_txn[7]);
6362                         check_spends!(node_txn[0], commitment_tx[0].clone());
6363                         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6364                         check_spends!(node_txn[1], chan_2.3.clone());
6365                         check_spends!(node_txn[2], node_txn[1].clone());
6366                         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6367                         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6368                         check_spends!(node_txn[3], chan_2.3.clone());
6369                         check_spends!(node_txn[4], node_txn[3].clone());
6370                         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
6371                         assert_eq!(node_txn[4].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6372                         timeout_tx = node_txn[0].clone();
6373                         node_txn.clear();
6374                 }
6375
6376                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![timeout_tx]}, 1);
6377                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6378                 check_added_monitors!(nodes[1], 1);
6379                 assert_eq!(events.len(), 2);
6380                 match events[0] {
6381                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6382                         _ => panic!("Unexpected event"),
6383                 }
6384                 match events[1] {
6385                         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, .. } } => {
6386                                 assert!(update_add_htlcs.is_empty());
6387                                 assert!(!update_fail_htlcs.is_empty());
6388                                 assert!(update_fulfill_htlcs.is_empty());
6389                                 assert!(update_fail_malformed_htlcs.is_empty());
6390                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6391                         },
6392                         _ => panic!("Unexpected event"),
6393                 };
6394                 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
6395                 assert_eq!(node_txn.len(), 0);
6396
6397                 // Broadcast legit commitment tx from B on A's chain
6398                 let commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6399                 check_spends!(commitment_tx[0], chan_1.3.clone());
6400
6401                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6402                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6403                 assert_eq!(events.len(), 1);
6404                 match events[0] {
6405                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6406                         _ => panic!("Unexpected event"),
6407                 }
6408                 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
6409                 assert_eq!(node_txn.len(), 4);
6410                 assert_eq!(node_txn[0], node_txn[3]);
6411                 check_spends!(node_txn[0], commitment_tx[0].clone());
6412                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6413                 check_spends!(node_txn[1], chan_1.3.clone());
6414                 check_spends!(node_txn[2], node_txn[1].clone());
6415                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6416                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6417         }
6418
6419         #[test]
6420         fn test_simple_commitment_revoked_fail_backward() {
6421                 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
6422                 // and fail backward accordingly.
6423
6424                 let nodes = create_network(3);
6425
6426                 // Create some initial channels
6427                 create_announced_chan_between_nodes(&nodes, 0, 1);
6428                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6429
6430                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6431                 // Get the will-be-revoked local txn from nodes[2]
6432                 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6433                 // Revoke the old state
6434                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6435
6436                 route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6437
6438                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6439                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6440                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6441                 check_added_monitors!(nodes[1], 1);
6442                 assert_eq!(events.len(), 2);
6443                 match events[0] {
6444                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6445                         _ => panic!("Unexpected event"),
6446                 }
6447                 match events[1] {
6448                         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, .. } } => {
6449                                 assert!(update_add_htlcs.is_empty());
6450                                 assert_eq!(update_fail_htlcs.len(), 1);
6451                                 assert!(update_fulfill_htlcs.is_empty());
6452                                 assert!(update_fail_malformed_htlcs.is_empty());
6453                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6454
6455                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6456                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6457
6458                                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6459                                 assert_eq!(events.len(), 1);
6460                                 match events[0] {
6461                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6462                                         _ => panic!("Unexpected event"),
6463                                 }
6464                                 let events = nodes[0].node.get_and_clear_pending_events();
6465                                 assert_eq!(events.len(), 1);
6466                                 match events[0] {
6467                                         Event::PaymentFailed { .. } => {},
6468                                         _ => panic!("Unexpected event"),
6469                                 }
6470                         },
6471                         _ => panic!("Unexpected event"),
6472                 }
6473         }
6474
6475         fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool) {
6476                 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
6477                 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
6478                 // commitment transaction anymore.
6479                 // To do this, we have the peer which will broadcast a revoked commitment transaction send
6480                 // a number of update_fail/commitment_signed updates without ever sending the RAA in
6481                 // response to our commitment_signed. This is somewhat misbehavior-y, though not
6482                 // technically disallowed and we should probably handle it reasonably.
6483                 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
6484                 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
6485                 // transactions:
6486                 // * Once we move it out of our holding cell/add it, we will immediately include it in a
6487                 //   commitment_signed (implying it will be in the latest remote commitment transaction).
6488                 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
6489                 //   and once they revoke the previous commitment transaction (allowing us to send a new
6490                 //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
6491                 let mut nodes = create_network(3);
6492
6493                 // Create some initial channels
6494                 create_announced_chan_between_nodes(&nodes, 0, 1);
6495                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6496
6497                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6498                 // Get the will-be-revoked local txn from nodes[2]
6499                 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6500                 // Revoke the old state
6501                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6502
6503                 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6504                 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6505                 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6506
6507                 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, 0));
6508                 check_added_monitors!(nodes[2], 1);
6509                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6510                 assert!(updates.update_add_htlcs.is_empty());
6511                 assert!(updates.update_fulfill_htlcs.is_empty());
6512                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6513                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6514                 assert!(updates.update_fee.is_none());
6515                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6516                 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
6517                 // Drop the last RAA from 3 -> 2
6518
6519                 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, 0));
6520                 check_added_monitors!(nodes[2], 1);
6521                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6522                 assert!(updates.update_add_htlcs.is_empty());
6523                 assert!(updates.update_fulfill_htlcs.is_empty());
6524                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6525                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6526                 assert!(updates.update_fee.is_none());
6527                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6528                 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6529                 check_added_monitors!(nodes[1], 1);
6530                 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
6531                 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6532                 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6533                 check_added_monitors!(nodes[2], 1);
6534
6535                 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, 0));
6536                 check_added_monitors!(nodes[2], 1);
6537                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6538                 assert!(updates.update_add_htlcs.is_empty());
6539                 assert!(updates.update_fulfill_htlcs.is_empty());
6540                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6541                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6542                 assert!(updates.update_fee.is_none());
6543                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6544                 // At this point first_payment_hash has dropped out of the latest two commitment
6545                 // transactions that nodes[1] is tracking...
6546                 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6547                 check_added_monitors!(nodes[1], 1);
6548                 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
6549                 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6550                 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6551                 check_added_monitors!(nodes[2], 1);
6552
6553                 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
6554                 // on nodes[2]'s RAA.
6555                 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
6556                 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6557                 nodes[1].node.send_payment(route, fourth_payment_hash).unwrap();
6558                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
6559                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6560                 check_added_monitors!(nodes[1], 0);
6561
6562                 if deliver_bs_raa {
6563                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa).unwrap();
6564                         // One monitor for the new revocation preimage, one as we generate a commitment for
6565                         // nodes[0] to fail first_payment_hash backwards.
6566                         check_added_monitors!(nodes[1], 2);
6567                 }
6568
6569                 let mut failed_htlcs = HashSet::new();
6570                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6571
6572                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6573                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6574
6575                 let events = nodes[1].node.get_and_clear_pending_events();
6576                 assert_eq!(events.len(), 1);
6577                 match events[0] {
6578                         Event::PaymentFailed { ref payment_hash, .. } => {
6579                                 assert_eq!(*payment_hash, fourth_payment_hash);
6580                         },
6581                         _ => panic!("Unexpected event"),
6582                 }
6583
6584                 if !deliver_bs_raa {
6585                         // If we delivered the RAA already then we already failed first_payment_hash backwards.
6586                         check_added_monitors!(nodes[1], 1);
6587                 }
6588
6589                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6590                 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
6591                 match events[if deliver_bs_raa { 2 } else { 0 }] {
6592                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6593                         _ => panic!("Unexpected event"),
6594                 }
6595                 if deliver_bs_raa {
6596                         match events[0] {
6597                                 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, .. } } => {
6598                                         assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
6599                                         assert_eq!(update_add_htlcs.len(), 1);
6600                                         assert!(update_fulfill_htlcs.is_empty());
6601                                         assert!(update_fail_htlcs.is_empty());
6602                                         assert!(update_fail_malformed_htlcs.is_empty());
6603                                 },
6604                                 _ => panic!("Unexpected event"),
6605                         }
6606                 }
6607                 // Due to the way backwards-failing occurs we do the updates in two steps.
6608                 let updates = match events[1] {
6609                         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, .. } } => {
6610                                 assert!(update_add_htlcs.is_empty());
6611                                 assert_eq!(update_fail_htlcs.len(), 1);
6612                                 assert!(update_fulfill_htlcs.is_empty());
6613                                 assert!(update_fail_malformed_htlcs.is_empty());
6614                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6615
6616                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6617                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
6618                                 check_added_monitors!(nodes[0], 1);
6619                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6620                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6621                                 check_added_monitors!(nodes[1], 1);
6622                                 let bs_second_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6623                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
6624                                 check_added_monitors!(nodes[1], 1);
6625                                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6626                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6627                                 check_added_monitors!(nodes[0], 1);
6628
6629                                 if !deliver_bs_raa {
6630                                         // If we delievered B's RAA we got an unknown preimage error, not something
6631                                         // that we should update our routing table for.
6632                                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6633                                         assert_eq!(events.len(), 1);
6634                                         match events[0] {
6635                                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6636                                                 _ => panic!("Unexpected event"),
6637                                         }
6638                                 }
6639                                 let events = nodes[0].node.get_and_clear_pending_events();
6640                                 assert_eq!(events.len(), 1);
6641                                 match events[0] {
6642                                         Event::PaymentFailed { ref payment_hash, .. } => {
6643                                                 assert!(failed_htlcs.insert(payment_hash.0));
6644                                         },
6645                                         _ => panic!("Unexpected event"),
6646                                 }
6647
6648                                 bs_second_update
6649                         },
6650                         _ => panic!("Unexpected event"),
6651                 };
6652
6653                 assert!(updates.update_add_htlcs.is_empty());
6654                 assert_eq!(updates.update_fail_htlcs.len(), 2);
6655                 assert!(updates.update_fulfill_htlcs.is_empty());
6656                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6657                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6658                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[1]).unwrap();
6659                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6660
6661                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6662                 assert_eq!(events.len(), 2);
6663                 for event in events {
6664                         match event {
6665                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6666                                 _ => panic!("Unexpected event"),
6667                         }
6668                 }
6669
6670                 let events = nodes[0].node.get_and_clear_pending_events();
6671                 assert_eq!(events.len(), 2);
6672                 match events[0] {
6673                         Event::PaymentFailed { ref payment_hash, .. } => {
6674                                 assert!(failed_htlcs.insert(payment_hash.0));
6675                         },
6676                         _ => panic!("Unexpected event"),
6677                 }
6678                 match events[1] {
6679                         Event::PaymentFailed { ref payment_hash, .. } => {
6680                                 assert!(failed_htlcs.insert(payment_hash.0));
6681                         },
6682                         _ => panic!("Unexpected event"),
6683                 }
6684
6685                 assert!(failed_htlcs.contains(&first_payment_hash.0));
6686                 assert!(failed_htlcs.contains(&second_payment_hash.0));
6687                 assert!(failed_htlcs.contains(&third_payment_hash.0));
6688         }
6689
6690         #[test]
6691         fn test_commitment_revoked_fail_backward_exhaustive() {
6692                 do_test_commitment_revoked_fail_backward_exhaustive(false);
6693                 do_test_commitment_revoked_fail_backward_exhaustive(true);
6694         }
6695
6696         #[test]
6697         fn test_htlc_ignore_latest_remote_commitment() {
6698                 // Test that HTLC transactions spending the latest remote commitment transaction are simply
6699                 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
6700                 let nodes = create_network(2);
6701                 create_announced_chan_between_nodes(&nodes, 0, 1);
6702
6703                 route_payment(&nodes[0], &[&nodes[1]], 10000000);
6704                 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
6705                 {
6706                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6707                         assert_eq!(events.len(), 1);
6708                         match events[0] {
6709                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6710                                         assert_eq!(flags & 0b10, 0b10);
6711                                 },
6712                                 _ => panic!("Unexpected event"),
6713                         }
6714                 }
6715
6716                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6717                 assert_eq!(node_txn.len(), 2);
6718
6719                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6720                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6721
6722                 {
6723                         let events = nodes[1].node.get_and_clear_pending_msg_events();
6724                         assert_eq!(events.len(), 1);
6725                         match events[0] {
6726                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6727                                         assert_eq!(flags & 0b10, 0b10);
6728                                 },
6729                                 _ => panic!("Unexpected event"),
6730                         }
6731                 }
6732
6733                 // Duplicate the block_connected call since this may happen due to other listeners
6734                 // registering new transactions
6735                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6736         }
6737
6738         #[test]
6739         fn test_force_close_fail_back() {
6740                 // Check which HTLCs are failed-backwards on channel force-closure
6741                 let mut nodes = create_network(3);
6742                 create_announced_chan_between_nodes(&nodes, 0, 1);
6743                 create_announced_chan_between_nodes(&nodes, 1, 2);
6744
6745                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
6746
6747                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6748
6749                 let mut payment_event = {
6750                         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6751                         check_added_monitors!(nodes[0], 1);
6752
6753                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6754                         assert_eq!(events.len(), 1);
6755                         SendEvent::from_event(events.remove(0))
6756                 };
6757
6758                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6759                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6760
6761                 let events_1 = nodes[1].node.get_and_clear_pending_events();
6762                 assert_eq!(events_1.len(), 1);
6763                 match events_1[0] {
6764                         Event::PendingHTLCsForwardable { .. } => { },
6765                         _ => panic!("Unexpected event"),
6766                 };
6767
6768                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
6769                 nodes[1].node.process_pending_htlc_forwards();
6770
6771                 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6772                 assert_eq!(events_2.len(), 1);
6773                 payment_event = SendEvent::from_event(events_2.remove(0));
6774                 assert_eq!(payment_event.msgs.len(), 1);
6775
6776                 check_added_monitors!(nodes[1], 1);
6777                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6778                 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
6779                 check_added_monitors!(nodes[2], 1);
6780                 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6781
6782                 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
6783                 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
6784                 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
6785
6786                 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
6787                 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6788                 assert_eq!(events_3.len(), 1);
6789                 match events_3[0] {
6790                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6791                                 assert_eq!(flags & 0b10, 0b10);
6792                         },
6793                         _ => panic!("Unexpected event"),
6794                 }
6795
6796                 let tx = {
6797                         let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6798                         // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
6799                         // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
6800                         // back to nodes[1] upon timeout otherwise.
6801                         assert_eq!(node_txn.len(), 1);
6802                         node_txn.remove(0)
6803                 };
6804
6805                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6806                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6807
6808                 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6809                 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
6810                 assert_eq!(events_4.len(), 1);
6811                 match events_4[0] {
6812                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6813                                 assert_eq!(flags & 0b10, 0b10);
6814                         },
6815                         _ => panic!("Unexpected event"),
6816                 }
6817
6818                 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
6819                 {
6820                         let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
6821                         monitors.get_mut(&OutPoint::new(Sha256dHash::from(&payment_event.commitment_msg.channel_id[..]), 0)).unwrap()
6822                                 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
6823                 }
6824                 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6825                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6826                 assert_eq!(node_txn.len(), 1);
6827                 assert_eq!(node_txn[0].input.len(), 1);
6828                 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
6829                 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
6830                 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
6831
6832                 check_spends!(node_txn[0], tx);
6833         }
6834
6835         #[test]
6836         fn test_unconf_chan() {
6837                 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
6838                 let nodes = create_network(2);
6839                 create_announced_chan_between_nodes(&nodes, 0, 1);
6840
6841                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6842                 assert_eq!(channel_state.by_id.len(), 1);
6843                 assert_eq!(channel_state.short_to_id.len(), 1);
6844                 mem::drop(channel_state);
6845
6846                 let mut headers = Vec::new();
6847                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6848                 headers.push(header.clone());
6849                 for _i in 2..100 {
6850                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6851                         headers.push(header.clone());
6852                 }
6853                 while !headers.is_empty() {
6854                         nodes[0].node.block_disconnected(&headers.pop().unwrap());
6855                 }
6856                 {
6857                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6858                         assert_eq!(events.len(), 1);
6859                         match events[0] {
6860                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6861                                         assert_eq!(flags & 0b10, 0b10);
6862                                 },
6863                                 _ => panic!("Unexpected event"),
6864                         }
6865                 }
6866                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6867                 assert_eq!(channel_state.by_id.len(), 0);
6868                 assert_eq!(channel_state.short_to_id.len(), 0);
6869         }
6870
6871         macro_rules! get_chan_reestablish_msgs {
6872                 ($src_node: expr, $dst_node: expr) => {
6873                         {
6874                                 let mut res = Vec::with_capacity(1);
6875                                 for msg in $src_node.node.get_and_clear_pending_msg_events() {
6876                                         if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
6877                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6878                                                 res.push(msg.clone());
6879                                         } else {
6880                                                 panic!("Unexpected event")
6881                                         }
6882                                 }
6883                                 res
6884                         }
6885                 }
6886         }
6887
6888         macro_rules! handle_chan_reestablish_msgs {
6889                 ($src_node: expr, $dst_node: expr) => {
6890                         {
6891                                 let msg_events = $src_node.node.get_and_clear_pending_msg_events();
6892                                 let mut idx = 0;
6893                                 let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
6894                                         idx += 1;
6895                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6896                                         Some(msg.clone())
6897                                 } else {
6898                                         None
6899                                 };
6900
6901                                 let mut revoke_and_ack = None;
6902                                 let mut commitment_update = None;
6903                                 let order = if let Some(ev) = msg_events.get(idx) {
6904                                         idx += 1;
6905                                         match ev {
6906                                                 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6907                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6908                                                         revoke_and_ack = Some(msg.clone());
6909                                                         RAACommitmentOrder::RevokeAndACKFirst
6910                                                 },
6911                                                 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6912                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6913                                                         commitment_update = Some(updates.clone());
6914                                                         RAACommitmentOrder::CommitmentFirst
6915                                                 },
6916                                                 _ => panic!("Unexpected event"),
6917                                         }
6918                                 } else {
6919                                         RAACommitmentOrder::CommitmentFirst
6920                                 };
6921
6922                                 if let Some(ev) = msg_events.get(idx) {
6923                                         match ev {
6924                                                 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6925                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6926                                                         assert!(revoke_and_ack.is_none());
6927                                                         revoke_and_ack = Some(msg.clone());
6928                                                 },
6929                                                 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6930                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6931                                                         assert!(commitment_update.is_none());
6932                                                         commitment_update = Some(updates.clone());
6933                                                 },
6934                                                 _ => panic!("Unexpected event"),
6935                                         }
6936                                 }
6937
6938                                 (funding_locked, revoke_and_ack, commitment_update, order)
6939                         }
6940                 }
6941         }
6942
6943         /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
6944         /// for claims/fails they are separated out.
6945         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)) {
6946                 node_a.node.peer_connected(&node_b.node.get_our_node_id());
6947                 let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
6948                 node_b.node.peer_connected(&node_a.node.get_our_node_id());
6949                 let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
6950
6951                 if send_funding_locked.0 {
6952                         // If a expects a funding_locked, it better not think it has received a revoke_and_ack
6953                         // from b
6954                         for reestablish in reestablish_1.iter() {
6955                                 assert_eq!(reestablish.next_remote_commitment_number, 0);
6956                         }
6957                 }
6958                 if send_funding_locked.1 {
6959                         // If b expects a funding_locked, it better not think it has received a revoke_and_ack
6960                         // from a
6961                         for reestablish in reestablish_2.iter() {
6962                                 assert_eq!(reestablish.next_remote_commitment_number, 0);
6963                         }
6964                 }
6965                 if send_funding_locked.0 || send_funding_locked.1 {
6966                         // If we expect any funding_locked's, both sides better have set
6967                         // next_local_commitment_number to 1
6968                         for reestablish in reestablish_1.iter() {
6969                                 assert_eq!(reestablish.next_local_commitment_number, 1);
6970                         }
6971                         for reestablish in reestablish_2.iter() {
6972                                 assert_eq!(reestablish.next_local_commitment_number, 1);
6973                         }
6974                 }
6975
6976                 let mut resp_1 = Vec::new();
6977                 for msg in reestablish_1 {
6978                         node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg).unwrap();
6979                         resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
6980                 }
6981                 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
6982                         check_added_monitors!(node_b, 1);
6983                 } else {
6984                         check_added_monitors!(node_b, 0);
6985                 }
6986
6987                 let mut resp_2 = Vec::new();
6988                 for msg in reestablish_2 {
6989                         node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg).unwrap();
6990                         resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
6991                 }
6992                 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
6993                         check_added_monitors!(node_a, 1);
6994                 } else {
6995                         check_added_monitors!(node_a, 0);
6996                 }
6997
6998                 // We dont yet support both needing updates, as that would require a different commitment dance:
6999                 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
7000                         (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
7001
7002                 for chan_msgs in resp_1.drain(..) {
7003                         if send_funding_locked.0 {
7004                                 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
7005                                 let announcement_event = node_a.node.get_and_clear_pending_msg_events();
7006                                 if !announcement_event.is_empty() {
7007                                         assert_eq!(announcement_event.len(), 1);
7008                                         if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
7009                                                 //TODO: Test announcement_sigs re-sending
7010                                         } else { panic!("Unexpected event!"); }
7011                                 }
7012                         } else {
7013                                 assert!(chan_msgs.0.is_none());
7014                         }
7015                         if pending_raa.0 {
7016                                 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
7017                                 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
7018                                 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
7019                                 check_added_monitors!(node_a, 1);
7020                         } else {
7021                                 assert!(chan_msgs.1.is_none());
7022                         }
7023                         if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
7024                                 let commitment_update = chan_msgs.2.unwrap();
7025                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
7026                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
7027                                 } else {
7028                                         assert!(commitment_update.update_add_htlcs.is_empty());
7029                                 }
7030                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
7031                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
7032                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
7033                                 for update_add in commitment_update.update_add_htlcs {
7034                                         node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add).unwrap();
7035                                 }
7036                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
7037                                         node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill).unwrap();
7038                                 }
7039                                 for update_fail in commitment_update.update_fail_htlcs {
7040                                         node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail).unwrap();
7041                                 }
7042
7043                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
7044                                         commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
7045                                 } else {
7046                                         node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
7047                                         check_added_monitors!(node_a, 1);
7048                                         let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
7049                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
7050                                         node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7051                                         assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
7052                                         check_added_monitors!(node_b, 1);
7053                                 }
7054                         } else {
7055                                 assert!(chan_msgs.2.is_none());
7056                         }
7057                 }
7058
7059                 for chan_msgs in resp_2.drain(..) {
7060                         if send_funding_locked.1 {
7061                                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
7062                                 let announcement_event = node_b.node.get_and_clear_pending_msg_events();
7063                                 if !announcement_event.is_empty() {
7064                                         assert_eq!(announcement_event.len(), 1);
7065                                         if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
7066                                                 //TODO: Test announcement_sigs re-sending
7067                                         } else { panic!("Unexpected event!"); }
7068                                 }
7069                         } else {
7070                                 assert!(chan_msgs.0.is_none());
7071                         }
7072                         if pending_raa.1 {
7073                                 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
7074                                 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
7075                                 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
7076                                 check_added_monitors!(node_b, 1);
7077                         } else {
7078                                 assert!(chan_msgs.1.is_none());
7079                         }
7080                         if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
7081                                 let commitment_update = chan_msgs.2.unwrap();
7082                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
7083                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
7084                                 }
7085                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
7086                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
7087                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
7088                                 for update_add in commitment_update.update_add_htlcs {
7089                                         node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add).unwrap();
7090                                 }
7091                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
7092                                         node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill).unwrap();
7093                                 }
7094                                 for update_fail in commitment_update.update_fail_htlcs {
7095                                         node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail).unwrap();
7096                                 }
7097
7098                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
7099                                         commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
7100                                 } else {
7101                                         node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
7102                                         check_added_monitors!(node_b, 1);
7103                                         let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
7104                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
7105                                         node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7106                                         assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
7107                                         check_added_monitors!(node_a, 1);
7108                                 }
7109                         } else {
7110                                 assert!(chan_msgs.2.is_none());
7111                         }
7112                 }
7113         }
7114
7115         #[test]
7116         fn test_simple_peer_disconnect() {
7117                 // Test that we can reconnect when there are no lost messages
7118                 let nodes = create_network(3);
7119                 create_announced_chan_between_nodes(&nodes, 0, 1);
7120                 create_announced_chan_between_nodes(&nodes, 1, 2);
7121
7122                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7123                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7124                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7125
7126                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7127                 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7128                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
7129                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
7130
7131                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7132                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7133                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7134
7135                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7136                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7137                 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7138                 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7139
7140                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7141                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7142
7143                 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3);
7144                 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
7145
7146                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
7147                 {
7148                         let events = nodes[0].node.get_and_clear_pending_events();
7149                         assert_eq!(events.len(), 2);
7150                         match events[0] {
7151                                 Event::PaymentSent { payment_preimage } => {
7152                                         assert_eq!(payment_preimage, payment_preimage_3);
7153                                 },
7154                                 _ => panic!("Unexpected event"),
7155                         }
7156                         match events[1] {
7157                                 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
7158                                         assert_eq!(payment_hash, payment_hash_5);
7159                                         assert!(rejected_by_dest);
7160                                 },
7161                                 _ => panic!("Unexpected event"),
7162                         }
7163                 }
7164
7165                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
7166                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
7167         }
7168
7169         fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
7170                 // Test that we can reconnect when in-flight HTLC updates get dropped
7171                 let mut nodes = create_network(2);
7172                 if messages_delivered == 0 {
7173                         create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
7174                         // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
7175                 } else {
7176                         create_announced_chan_between_nodes(&nodes, 0, 1);
7177                 }
7178
7179                 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();
7180                 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7181
7182                 let payment_event = {
7183                         nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
7184                         check_added_monitors!(nodes[0], 1);
7185
7186                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7187                         assert_eq!(events.len(), 1);
7188                         SendEvent::from_event(events.remove(0))
7189                 };
7190                 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
7191
7192                 if messages_delivered < 2 {
7193                         // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
7194                 } else {
7195                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7196                         if messages_delivered >= 3 {
7197                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7198                                 check_added_monitors!(nodes[1], 1);
7199                                 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7200
7201                                 if messages_delivered >= 4 {
7202                                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7203                                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7204                                         check_added_monitors!(nodes[0], 1);
7205
7206                                         if messages_delivered >= 5 {
7207                                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
7208                                                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7209                                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7210                                                 check_added_monitors!(nodes[0], 1);
7211
7212                                                 if messages_delivered >= 6 {
7213                                                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7214                                                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7215                                                         check_added_monitors!(nodes[1], 1);
7216                                                 }
7217                                         }
7218                                 }
7219                         }
7220                 }
7221
7222                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7223                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7224                 if messages_delivered < 3 {
7225                         // Even if the funding_locked messages get exchanged, as long as nothing further was
7226                         // received on either side, both sides will need to resend them.
7227                         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
7228                 } else if messages_delivered == 3 {
7229                         // nodes[0] still wants its RAA + commitment_signed
7230                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
7231                 } else if messages_delivered == 4 {
7232                         // nodes[0] still wants its commitment_signed
7233                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
7234                 } else if messages_delivered == 5 {
7235                         // nodes[1] still wants its final RAA
7236                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
7237                 } else if messages_delivered == 6 {
7238                         // Everything was delivered...
7239                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7240                 }
7241
7242                 let events_1 = nodes[1].node.get_and_clear_pending_events();
7243                 assert_eq!(events_1.len(), 1);
7244                 match events_1[0] {
7245                         Event::PendingHTLCsForwardable { .. } => { },
7246                         _ => panic!("Unexpected event"),
7247                 };
7248
7249                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7250                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7251                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7252
7253                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7254                 nodes[1].node.process_pending_htlc_forwards();
7255
7256                 let events_2 = nodes[1].node.get_and_clear_pending_events();
7257                 assert_eq!(events_2.len(), 1);
7258                 match events_2[0] {
7259                         Event::PaymentReceived { ref payment_hash, amt } => {
7260                                 assert_eq!(payment_hash_1, *payment_hash);
7261                                 assert_eq!(amt, 1000000);
7262                         },
7263                         _ => panic!("Unexpected event"),
7264                 }
7265
7266                 nodes[1].node.claim_funds(payment_preimage_1);
7267                 check_added_monitors!(nodes[1], 1);
7268
7269                 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
7270                 assert_eq!(events_3.len(), 1);
7271                 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
7272                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
7273                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7274                                 assert!(updates.update_add_htlcs.is_empty());
7275                                 assert!(updates.update_fail_htlcs.is_empty());
7276                                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
7277                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
7278                                 assert!(updates.update_fee.is_none());
7279                                 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
7280                         },
7281                         _ => panic!("Unexpected event"),
7282                 };
7283
7284                 if messages_delivered >= 1 {
7285                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc).unwrap();
7286
7287                         let events_4 = nodes[0].node.get_and_clear_pending_events();
7288                         assert_eq!(events_4.len(), 1);
7289                         match events_4[0] {
7290                                 Event::PaymentSent { ref payment_preimage } => {
7291                                         assert_eq!(payment_preimage_1, *payment_preimage);
7292                                 },
7293                                 _ => panic!("Unexpected event"),
7294                         }
7295
7296                         if messages_delivered >= 2 {
7297                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
7298                                 check_added_monitors!(nodes[0], 1);
7299                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7300
7301                                 if messages_delivered >= 3 {
7302                                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7303                                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7304                                         check_added_monitors!(nodes[1], 1);
7305
7306                                         if messages_delivered >= 4 {
7307                                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
7308                                                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7309                                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7310                                                 check_added_monitors!(nodes[1], 1);
7311
7312                                                 if messages_delivered >= 5 {
7313                                                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7314                                                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7315                                                         check_added_monitors!(nodes[0], 1);
7316                                                 }
7317                                         }
7318                                 }
7319                         }
7320                 }
7321
7322                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7323                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7324                 if messages_delivered < 2 {
7325                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
7326                         //TODO: Deduplicate PaymentSent events, then enable this if:
7327                         //if messages_delivered < 1 {
7328                                 let events_4 = nodes[0].node.get_and_clear_pending_events();
7329                                 assert_eq!(events_4.len(), 1);
7330                                 match events_4[0] {
7331                                         Event::PaymentSent { ref payment_preimage } => {
7332                                                 assert_eq!(payment_preimage_1, *payment_preimage);
7333                                         },
7334                                         _ => panic!("Unexpected event"),
7335                                 }
7336                         //}
7337                 } else if messages_delivered == 2 {
7338                         // nodes[0] still wants its RAA + commitment_signed
7339                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
7340                 } else if messages_delivered == 3 {
7341                         // nodes[0] still wants its commitment_signed
7342                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
7343                 } else if messages_delivered == 4 {
7344                         // nodes[1] still wants its final RAA
7345                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
7346                 } else if messages_delivered == 5 {
7347                         // Everything was delivered...
7348                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7349                 }
7350
7351                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7352                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7353                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7354
7355                 // Channel should still work fine...
7356                 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
7357                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7358         }
7359
7360         #[test]
7361         fn test_drop_messages_peer_disconnect_a() {
7362                 do_test_drop_messages_peer_disconnect(0);
7363                 do_test_drop_messages_peer_disconnect(1);
7364                 do_test_drop_messages_peer_disconnect(2);
7365                 do_test_drop_messages_peer_disconnect(3);
7366         }
7367
7368         #[test]
7369         fn test_drop_messages_peer_disconnect_b() {
7370                 do_test_drop_messages_peer_disconnect(4);
7371                 do_test_drop_messages_peer_disconnect(5);
7372                 do_test_drop_messages_peer_disconnect(6);
7373         }
7374
7375         #[test]
7376         fn test_funding_peer_disconnect() {
7377                 // Test that we can lock in our funding tx while disconnected
7378                 let nodes = create_network(2);
7379                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
7380
7381                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7382                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7383
7384                 confirm_transaction(&nodes[0].chain_monitor, &tx, tx.version);
7385                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7386                 assert_eq!(events_1.len(), 1);
7387                 match events_1[0] {
7388                         MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7389                                 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7390                         },
7391                         _ => panic!("Unexpected event"),
7392                 }
7393
7394                 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7395
7396                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7397                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7398
7399                 confirm_transaction(&nodes[1].chain_monitor, &tx, tx.version);
7400                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7401                 assert_eq!(events_2.len(), 2);
7402                 match events_2[0] {
7403                         MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7404                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7405                         },
7406                         _ => panic!("Unexpected event"),
7407                 }
7408                 match events_2[1] {
7409                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ } => {
7410                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7411                         },
7412                         _ => panic!("Unexpected event"),
7413                 }
7414
7415                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7416
7417                 // TODO: We shouldn't need to manually pass list_usable_chanels here once we support
7418                 // rebroadcasting announcement_signatures upon reconnect.
7419
7420                 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();
7421                 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
7422                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
7423         }
7424
7425         #[test]
7426         fn test_drop_messages_peer_disconnect_dual_htlc() {
7427                 // Test that we can handle reconnecting when both sides of a channel have pending
7428                 // commitment_updates when we disconnect.
7429                 let mut nodes = create_network(2);
7430                 create_announced_chan_between_nodes(&nodes, 0, 1);
7431
7432                 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7433
7434                 // Now try to send a second payment which will fail to send
7435                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7436                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7437
7438                 nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
7439                 check_added_monitors!(nodes[0], 1);
7440
7441                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7442                 assert_eq!(events_1.len(), 1);
7443                 match events_1[0] {
7444                         MessageSendEvent::UpdateHTLCs { .. } => {},
7445                         _ => panic!("Unexpected event"),
7446                 }
7447
7448                 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7449                 check_added_monitors!(nodes[1], 1);
7450
7451                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7452                 assert_eq!(events_2.len(), 1);
7453                 match events_2[0] {
7454                         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 } } => {
7455                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7456                                 assert!(update_add_htlcs.is_empty());
7457                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7458                                 assert!(update_fail_htlcs.is_empty());
7459                                 assert!(update_fail_malformed_htlcs.is_empty());
7460                                 assert!(update_fee.is_none());
7461
7462                                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7463                                 let events_3 = nodes[0].node.get_and_clear_pending_events();
7464                                 assert_eq!(events_3.len(), 1);
7465                                 match events_3[0] {
7466                                         Event::PaymentSent { ref payment_preimage } => {
7467                                                 assert_eq!(*payment_preimage, payment_preimage_1);
7468                                         },
7469                                         _ => panic!("Unexpected event"),
7470                                 }
7471
7472                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
7473                                 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7474                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7475                                 check_added_monitors!(nodes[0], 1);
7476                         },
7477                         _ => panic!("Unexpected event"),
7478                 }
7479
7480                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7481                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7482
7483                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7484                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7485                 assert_eq!(reestablish_1.len(), 1);
7486                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7487                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7488                 assert_eq!(reestablish_2.len(), 1);
7489
7490                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7491                 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7492                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7493                 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7494
7495                 assert!(as_resp.0.is_none());
7496                 assert!(bs_resp.0.is_none());
7497
7498                 assert!(bs_resp.1.is_none());
7499                 assert!(bs_resp.2.is_none());
7500
7501                 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7502
7503                 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
7504                 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
7505                 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7506                 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7507                 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
7508                 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();
7509                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7510                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7511                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7512                 check_added_monitors!(nodes[1], 1);
7513
7514                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap();
7515                 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7516                 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
7517                 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
7518                 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
7519                 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
7520                 assert!(bs_second_commitment_signed.update_fee.is_none());
7521                 check_added_monitors!(nodes[1], 1);
7522
7523                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7524                 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7525                 assert!(as_commitment_signed.update_add_htlcs.is_empty());
7526                 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
7527                 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
7528                 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
7529                 assert!(as_commitment_signed.update_fee.is_none());
7530                 check_added_monitors!(nodes[0], 1);
7531
7532                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
7533                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7534                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7535                 check_added_monitors!(nodes[0], 1);
7536
7537                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
7538                 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7539                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7540                 check_added_monitors!(nodes[1], 1);
7541
7542                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7543                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7544                 check_added_monitors!(nodes[1], 1);
7545
7546                 let events_4 = nodes[1].node.get_and_clear_pending_events();
7547                 assert_eq!(events_4.len(), 1);
7548                 match events_4[0] {
7549                         Event::PendingHTLCsForwardable { .. } => { },
7550                         _ => panic!("Unexpected event"),
7551                 };
7552
7553                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7554                 nodes[1].node.process_pending_htlc_forwards();
7555
7556                 let events_5 = nodes[1].node.get_and_clear_pending_events();
7557                 assert_eq!(events_5.len(), 1);
7558                 match events_5[0] {
7559                         Event::PaymentReceived { ref payment_hash, amt: _ } => {
7560                                 assert_eq!(payment_hash_2, *payment_hash);
7561                         },
7562                         _ => panic!("Unexpected event"),
7563                 }
7564
7565                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
7566                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7567                 check_added_monitors!(nodes[0], 1);
7568
7569                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7570         }
7571
7572         #[test]
7573         fn test_simple_monitor_permanent_update_fail() {
7574                 // Test that we handle a simple permanent monitor update failure
7575                 let mut nodes = create_network(2);
7576                 create_announced_chan_between_nodes(&nodes, 0, 1);
7577
7578                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7579                 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7580
7581                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7582                 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route, payment_hash_1) {} else { panic!(); }
7583                 check_added_monitors!(nodes[0], 1);
7584
7585                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7586                 assert_eq!(events_1.len(), 2);
7587                 match events_1[0] {
7588                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7589                         _ => panic!("Unexpected event"),
7590                 };
7591                 match events_1[1] {
7592                         MessageSendEvent::HandleError { node_id, .. } => assert_eq!(node_id, nodes[1].node.get_our_node_id()),
7593                         _ => panic!("Unexpected event"),
7594                 };
7595
7596                 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7597                 // PaymentFailed event
7598
7599                 assert_eq!(nodes[0].node.list_channels().len(), 0);
7600         }
7601
7602         fn do_test_simple_monitor_temporary_update_fail(disconnect: bool) {
7603                 // Test that we can recover from a simple temporary monitor update failure optionally with
7604                 // a disconnect in between
7605                 let mut nodes = create_network(2);
7606                 create_announced_chan_between_nodes(&nodes, 0, 1);
7607
7608                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7609                 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7610
7611                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7612                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_1) {} else { panic!(); }
7613                 check_added_monitors!(nodes[0], 1);
7614
7615                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7616                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7617                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7618
7619                 if disconnect {
7620                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7621                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7622                         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7623                 }
7624
7625                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7626                 nodes[0].node.test_restore_channel_monitor();
7627                 check_added_monitors!(nodes[0], 1);
7628
7629                 let mut events_2 = nodes[0].node.get_and_clear_pending_msg_events();
7630                 assert_eq!(events_2.len(), 1);
7631                 let payment_event = SendEvent::from_event(events_2.pop().unwrap());
7632                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7633                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7634                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7635
7636                 expect_pending_htlcs_forwardable!(nodes[1]);
7637
7638                 let events_3 = nodes[1].node.get_and_clear_pending_events();
7639                 assert_eq!(events_3.len(), 1);
7640                 match events_3[0] {
7641                         Event::PaymentReceived { ref payment_hash, amt } => {
7642                                 assert_eq!(payment_hash_1, *payment_hash);
7643                                 assert_eq!(amt, 1000000);
7644                         },
7645                         _ => panic!("Unexpected event"),
7646                 }
7647
7648                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_1);
7649
7650                 // Now set it to failed again...
7651                 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7652                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7653                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route, payment_hash_2) {} else { panic!(); }
7654                 check_added_monitors!(nodes[0], 1);
7655
7656                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7657                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7658                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7659
7660                 if disconnect {
7661                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7662                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7663                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7664                 }
7665
7666                 // ...and make sure we can force-close a TemporaryFailure channel with a PermanentFailure
7667                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7668                 nodes[0].node.test_restore_channel_monitor();
7669                 check_added_monitors!(nodes[0], 1);
7670
7671                 let events_5 = nodes[0].node.get_and_clear_pending_msg_events();
7672                 assert_eq!(events_5.len(), 1);
7673                 match events_5[0] {
7674                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7675                         _ => panic!("Unexpected event"),
7676                 }
7677
7678                 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7679                 // PaymentFailed event
7680
7681                 assert_eq!(nodes[0].node.list_channels().len(), 0);
7682         }
7683
7684         #[test]
7685         fn test_simple_monitor_temporary_update_fail() {
7686                 do_test_simple_monitor_temporary_update_fail(false);
7687                 do_test_simple_monitor_temporary_update_fail(true);
7688         }
7689
7690         fn do_test_monitor_temporary_update_fail(disconnect_count: usize) {
7691                 let disconnect_flags = 8 | 16;
7692
7693                 // Test that we can recover from a temporary monitor update failure with some in-flight
7694                 // HTLCs going on at the same time potentially with some disconnection thrown in.
7695                 // * First we route a payment, then get a temporary monitor update failure when trying to
7696                 //   route a second payment. We then claim the first payment.
7697                 // * If disconnect_count is set, we will disconnect at this point (which is likely as
7698                 //   TemporaryFailure likely indicates net disconnect which resulted in failing to update
7699                 //   the ChannelMonitor on a watchtower).
7700                 // * If !(disconnect_count & 16) we deliver a update_fulfill_htlc/CS for the first payment
7701                 //   immediately, otherwise we wait sconnect and deliver them via the reconnect
7702                 //   channel_reestablish processing (ie disconnect_count & 16 makes no sense if
7703                 //   disconnect_count & !disconnect_flags is 0).
7704                 // * We then update the channel monitor, reconnecting if disconnect_count is set and walk
7705                 //   through message sending, potentially disconnect/reconnecting multiple times based on
7706                 //   disconnect_count, to get the update_fulfill_htlc through.
7707                 // * We then walk through more message exchanges to get the original update_add_htlc
7708                 //   through, swapping message ordering based on disconnect_count & 8 and optionally
7709                 //   disconnect/reconnecting based on disconnect_count.
7710                 let mut nodes = create_network(2);
7711                 create_announced_chan_between_nodes(&nodes, 0, 1);
7712
7713                 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7714
7715                 // Now try to send a second payment which will fail to send
7716                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7717                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7718
7719                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7720                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_2) {} else { panic!(); }
7721                 check_added_monitors!(nodes[0], 1);
7722
7723                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7724                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7725                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7726
7727                 // Claim the previous payment, which will result in a update_fulfill_htlc/CS from nodes[1]
7728                 // but nodes[0] won't respond since it is frozen.
7729                 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7730                 check_added_monitors!(nodes[1], 1);
7731                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7732                 assert_eq!(events_2.len(), 1);
7733                 let (bs_initial_fulfill, bs_initial_commitment_signed) = match events_2[0] {
7734                         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 } } => {
7735                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7736                                 assert!(update_add_htlcs.is_empty());
7737                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7738                                 assert!(update_fail_htlcs.is_empty());
7739                                 assert!(update_fail_malformed_htlcs.is_empty());
7740                                 assert!(update_fee.is_none());
7741
7742                                 if (disconnect_count & 16) == 0 {
7743                                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7744                                         let events_3 = nodes[0].node.get_and_clear_pending_events();
7745                                         assert_eq!(events_3.len(), 1);
7746                                         match events_3[0] {
7747                                                 Event::PaymentSent { ref payment_preimage } => {
7748                                                         assert_eq!(*payment_preimage, payment_preimage_1);
7749                                                 },
7750                                                 _ => panic!("Unexpected event"),
7751                                         }
7752
7753                                         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) {
7754                                                 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
7755                                         } else { panic!(); }
7756                                 }
7757
7758                                 (update_fulfill_htlcs[0].clone(), commitment_signed.clone())
7759                         },
7760                         _ => panic!("Unexpected event"),
7761                 };
7762
7763                 if disconnect_count & !disconnect_flags > 0 {
7764                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7765                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7766                 }
7767
7768                 // Now fix monitor updating...
7769                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7770                 nodes[0].node.test_restore_channel_monitor();
7771                 check_added_monitors!(nodes[0], 1);
7772
7773                 macro_rules! disconnect_reconnect_peers { () => { {
7774                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7775                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7776
7777                         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7778                         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7779                         assert_eq!(reestablish_1.len(), 1);
7780                         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7781                         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7782                         assert_eq!(reestablish_2.len(), 1);
7783
7784                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7785                         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7786                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7787                         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7788
7789                         assert!(as_resp.0.is_none());
7790                         assert!(bs_resp.0.is_none());
7791
7792                         (reestablish_1, reestablish_2, as_resp, bs_resp)
7793                 } } }
7794
7795                 let (payment_event, initial_revoke_and_ack) = if disconnect_count & !disconnect_flags > 0 {
7796                         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7797                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7798
7799                         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7800                         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7801                         assert_eq!(reestablish_1.len(), 1);
7802                         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7803                         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7804                         assert_eq!(reestablish_2.len(), 1);
7805
7806                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7807                         check_added_monitors!(nodes[0], 0);
7808                         let mut as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7809                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7810                         check_added_monitors!(nodes[1], 0);
7811                         let mut bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7812
7813                         assert!(as_resp.0.is_none());
7814                         assert!(bs_resp.0.is_none());
7815
7816                         assert!(bs_resp.1.is_none());
7817                         if (disconnect_count & 16) == 0 {
7818                                 assert!(bs_resp.2.is_none());
7819
7820                                 assert!(as_resp.1.is_some());
7821                                 assert!(as_resp.2.is_some());
7822                                 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7823                         } else {
7824                                 assert!(bs_resp.2.as_ref().unwrap().update_add_htlcs.is_empty());
7825                                 assert!(bs_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7826                                 assert!(bs_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7827                                 assert!(bs_resp.2.as_ref().unwrap().update_fee.is_none());
7828                                 assert!(bs_resp.2.as_ref().unwrap().update_fulfill_htlcs == vec![bs_initial_fulfill]);
7829                                 assert!(bs_resp.2.as_ref().unwrap().commitment_signed == bs_initial_commitment_signed);
7830
7831                                 assert!(as_resp.1.is_none());
7832
7833                                 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();
7834                                 let events_3 = nodes[0].node.get_and_clear_pending_events();
7835                                 assert_eq!(events_3.len(), 1);
7836                                 match events_3[0] {
7837                                         Event::PaymentSent { ref payment_preimage } => {
7838                                                 assert_eq!(*payment_preimage, payment_preimage_1);
7839                                         },
7840                                         _ => panic!("Unexpected event"),
7841                                 }
7842
7843                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7844                                 let as_resp_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7845                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7846                                 check_added_monitors!(nodes[0], 1);
7847
7848                                 as_resp.1 = Some(as_resp_raa);
7849                                 bs_resp.2 = None;
7850                         }
7851
7852                         if disconnect_count & !disconnect_flags > 1 {
7853                                 let (second_reestablish_1, second_reestablish_2, second_as_resp, second_bs_resp) = disconnect_reconnect_peers!();
7854
7855                                 if (disconnect_count & 16) == 0 {
7856                                         assert!(reestablish_1 == second_reestablish_1);
7857                                         assert!(reestablish_2 == second_reestablish_2);
7858                                 }
7859                                 assert!(as_resp == second_as_resp);
7860                                 assert!(bs_resp == second_bs_resp);
7861                         }
7862
7863                         (SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), as_resp.2.unwrap()), as_resp.1.unwrap())
7864                 } else {
7865                         let mut events_4 = nodes[0].node.get_and_clear_pending_msg_events();
7866                         assert_eq!(events_4.len(), 2);
7867                         (SendEvent::from_event(events_4.remove(0)), match events_4[0] {
7868                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
7869                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7870                                         msg.clone()
7871                                 },
7872                                 _ => panic!("Unexpected event"),
7873                         })
7874                 };
7875
7876                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7877
7878                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7879                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7880                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7881                 // nodes[1] is awaiting an RAA from nodes[0] still so get_event_msg's assert(len == 1) passes
7882                 check_added_monitors!(nodes[1], 1);
7883
7884                 if disconnect_count & !disconnect_flags > 2 {
7885                         let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7886
7887                         assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7888                         assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7889
7890                         assert!(as_resp.2.is_none());
7891                         assert!(bs_resp.2.is_none());
7892                 }
7893
7894                 let as_commitment_update;
7895                 let bs_second_commitment_update;
7896
7897                 macro_rules! handle_bs_raa { () => {
7898                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7899                         as_commitment_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7900                         assert!(as_commitment_update.update_add_htlcs.is_empty());
7901                         assert!(as_commitment_update.update_fulfill_htlcs.is_empty());
7902                         assert!(as_commitment_update.update_fail_htlcs.is_empty());
7903                         assert!(as_commitment_update.update_fail_malformed_htlcs.is_empty());
7904                         assert!(as_commitment_update.update_fee.is_none());
7905                         check_added_monitors!(nodes[0], 1);
7906                 } }
7907
7908                 macro_rules! handle_initial_raa { () => {
7909                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &initial_revoke_and_ack).unwrap();
7910                         bs_second_commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7911                         assert!(bs_second_commitment_update.update_add_htlcs.is_empty());
7912                         assert!(bs_second_commitment_update.update_fulfill_htlcs.is_empty());
7913                         assert!(bs_second_commitment_update.update_fail_htlcs.is_empty());
7914                         assert!(bs_second_commitment_update.update_fail_malformed_htlcs.is_empty());
7915                         assert!(bs_second_commitment_update.update_fee.is_none());
7916                         check_added_monitors!(nodes[1], 1);
7917                 } }
7918
7919                 if (disconnect_count & 8) == 0 {
7920                         handle_bs_raa!();
7921
7922                         if disconnect_count & !disconnect_flags > 3 {
7923                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7924
7925                                 assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7926                                 assert!(bs_resp.1.is_none());
7927
7928                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7929                                 assert!(bs_resp.2.is_none());
7930
7931                                 assert!(as_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7932                         }
7933
7934                         handle_initial_raa!();
7935
7936                         if disconnect_count & !disconnect_flags > 4 {
7937                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7938
7939                                 assert!(as_resp.1.is_none());
7940                                 assert!(bs_resp.1.is_none());
7941
7942                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7943                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7944                         }
7945                 } else {
7946                         handle_initial_raa!();
7947
7948                         if disconnect_count & !disconnect_flags > 3 {
7949                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7950
7951                                 assert!(as_resp.1.is_none());
7952                                 assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7953
7954                                 assert!(as_resp.2.is_none());
7955                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7956
7957                                 assert!(bs_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7958                         }
7959
7960                         handle_bs_raa!();
7961
7962                         if disconnect_count & !disconnect_flags > 4 {
7963                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7964
7965                                 assert!(as_resp.1.is_none());
7966                                 assert!(bs_resp.1.is_none());
7967
7968                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7969                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7970                         }
7971                 }
7972
7973                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_update.commitment_signed).unwrap();
7974                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7975                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7976                 check_added_monitors!(nodes[0], 1);
7977
7978                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_update.commitment_signed).unwrap();
7979                 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7980                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7981                 check_added_monitors!(nodes[1], 1);
7982
7983                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7984                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7985                 check_added_monitors!(nodes[1], 1);
7986
7987                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
7988                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7989                 check_added_monitors!(nodes[0], 1);
7990
7991                 expect_pending_htlcs_forwardable!(nodes[1]);
7992
7993                 let events_5 = nodes[1].node.get_and_clear_pending_events();
7994                 assert_eq!(events_5.len(), 1);
7995                 match events_5[0] {
7996                         Event::PaymentReceived { ref payment_hash, amt } => {
7997                                 assert_eq!(payment_hash_2, *payment_hash);
7998                                 assert_eq!(amt, 1000000);
7999                         },
8000                         _ => panic!("Unexpected event"),
8001                 }
8002
8003                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
8004         }
8005
8006         #[test]
8007         fn test_monitor_temporary_update_fail_a() {
8008                 do_test_monitor_temporary_update_fail(0);
8009                 do_test_monitor_temporary_update_fail(1);
8010                 do_test_monitor_temporary_update_fail(2);
8011                 do_test_monitor_temporary_update_fail(3);
8012                 do_test_monitor_temporary_update_fail(4);
8013                 do_test_monitor_temporary_update_fail(5);
8014         }
8015
8016         #[test]
8017         fn test_monitor_temporary_update_fail_b() {
8018                 do_test_monitor_temporary_update_fail(2 | 8);
8019                 do_test_monitor_temporary_update_fail(3 | 8);
8020                 do_test_monitor_temporary_update_fail(4 | 8);
8021                 do_test_monitor_temporary_update_fail(5 | 8);
8022         }
8023
8024         #[test]
8025         fn test_monitor_temporary_update_fail_c() {
8026                 do_test_monitor_temporary_update_fail(1 | 16);
8027                 do_test_monitor_temporary_update_fail(2 | 16);
8028                 do_test_monitor_temporary_update_fail(3 | 16);
8029                 do_test_monitor_temporary_update_fail(2 | 8 | 16);
8030                 do_test_monitor_temporary_update_fail(3 | 8 | 16);
8031         }
8032
8033         #[test]
8034         fn test_monitor_update_fail_cs() {
8035                 // Tests handling of a monitor update failure when processing an incoming commitment_signed
8036                 let mut nodes = create_network(2);
8037                 create_announced_chan_between_nodes(&nodes, 0, 1);
8038
8039                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8040                 let (payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
8041                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
8042                 check_added_monitors!(nodes[0], 1);
8043
8044                 let send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8045                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8046
8047                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8048                 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() {
8049                         assert_eq!(err, "Failed to update ChannelMonitor");
8050                 } else { panic!(); }
8051                 check_added_monitors!(nodes[1], 1);
8052                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8053
8054                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8055                 nodes[1].node.test_restore_channel_monitor();
8056                 check_added_monitors!(nodes[1], 1);
8057                 let responses = nodes[1].node.get_and_clear_pending_msg_events();
8058                 assert_eq!(responses.len(), 2);
8059
8060                 match responses[0] {
8061                         MessageSendEvent::SendRevokeAndACK { ref msg, ref node_id } => {
8062                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8063                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &msg).unwrap();
8064                                 check_added_monitors!(nodes[0], 1);
8065                         },
8066                         _ => panic!("Unexpected event"),
8067                 }
8068                 match responses[1] {
8069                         MessageSendEvent::UpdateHTLCs { ref updates, ref node_id } => {
8070                                 assert!(updates.update_add_htlcs.is_empty());
8071                                 assert!(updates.update_fulfill_htlcs.is_empty());
8072                                 assert!(updates.update_fail_htlcs.is_empty());
8073                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8074                                 assert!(updates.update_fee.is_none());
8075                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8076
8077                                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8078                                 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() {
8079                                         assert_eq!(err, "Failed to update ChannelMonitor");
8080                                 } else { panic!(); }
8081                                 check_added_monitors!(nodes[0], 1);
8082                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8083                         },
8084                         _ => panic!("Unexpected event"),
8085                 }
8086
8087                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
8088                 nodes[0].node.test_restore_channel_monitor();
8089                 check_added_monitors!(nodes[0], 1);
8090
8091                 let final_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8092                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &final_raa).unwrap();
8093                 check_added_monitors!(nodes[1], 1);
8094
8095                 let mut events = nodes[1].node.get_and_clear_pending_events();
8096                 assert_eq!(events.len(), 1);
8097                 match events[0] {
8098                         Event::PendingHTLCsForwardable { .. } => { },
8099                         _ => panic!("Unexpected event"),
8100                 };
8101                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8102                 nodes[1].node.process_pending_htlc_forwards();
8103
8104                 events = nodes[1].node.get_and_clear_pending_events();
8105                 assert_eq!(events.len(), 1);
8106                 match events[0] {
8107                         Event::PaymentReceived { payment_hash, amt } => {
8108                                 assert_eq!(payment_hash, our_payment_hash);
8109                                 assert_eq!(amt, 1000000);
8110                         },
8111                         _ => panic!("Unexpected event"),
8112                 };
8113
8114                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
8115         }
8116
8117         fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) {
8118                 // Tests handling of a monitor update failure when processing an incoming RAA
8119                 let mut nodes = create_network(3);
8120                 create_announced_chan_between_nodes(&nodes, 0, 1);
8121                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
8122
8123                 // Rebalance a bit so that we can send backwards from 2 to 1.
8124                 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 5000000);
8125
8126                 // Route a first payment that we'll fail backwards
8127                 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
8128
8129                 // Fail the payment backwards, failing the monitor update on nodes[1]'s receipt of the RAA
8130                 assert!(nodes[2].node.fail_htlc_backwards(&payment_hash_1, 0));
8131                 check_added_monitors!(nodes[2], 1);
8132
8133                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8134                 assert!(updates.update_add_htlcs.is_empty());
8135                 assert!(updates.update_fulfill_htlcs.is_empty());
8136                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8137                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8138                 assert!(updates.update_fee.is_none());
8139                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
8140
8141                 let bs_revoke_and_ack = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
8142                 check_added_monitors!(nodes[0], 0);
8143
8144                 // While the second channel is AwaitingRAA, forward a second payment to get it into the
8145                 // holding cell.
8146                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
8147                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8148                 nodes[0].node.send_payment(route, payment_hash_2).unwrap();
8149                 check_added_monitors!(nodes[0], 1);
8150
8151                 let mut send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8152                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8153                 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false);
8154
8155                 let events_1 = nodes[1].node.get_and_clear_pending_events();
8156                 assert_eq!(events_1.len(), 1);
8157                 match events_1[0] {
8158                         Event::PendingHTLCsForwardable { .. } => { },
8159                         _ => panic!("Unexpected event"),
8160                 };
8161
8162                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8163                 nodes[1].node.process_pending_htlc_forwards();
8164                 check_added_monitors!(nodes[1], 0);
8165                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8166
8167                 // Now fail monitor updating.
8168                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8169                 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() {
8170                         assert_eq!(err, "Failed to update ChannelMonitor");
8171                 } else { panic!(); }
8172                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8173                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8174                 check_added_monitors!(nodes[1], 1);
8175
8176                 // Attempt to forward a third payment but fail due to the second channel being unavailable
8177                 // for forwarding.
8178
8179                 let (_, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
8180                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8181                 nodes[0].node.send_payment(route, payment_hash_3).unwrap();
8182                 check_added_monitors!(nodes[0], 1);
8183
8184                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(()); // We succeed in updating the monitor for the first channel
8185                 send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8186                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8187                 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
8188                 check_added_monitors!(nodes[1], 0);
8189
8190                 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8191                 assert_eq!(events_2.len(), 1);
8192                 match events_2.remove(0) {
8193                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
8194                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8195                                 assert!(updates.update_fulfill_htlcs.is_empty());
8196                                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8197                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8198                                 assert!(updates.update_add_htlcs.is_empty());
8199                                 assert!(updates.update_fee.is_none());
8200
8201                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
8202                                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
8203
8204                                 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
8205                                 assert_eq!(msg_events.len(), 1);
8206                                 match msg_events[0] {
8207                                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
8208                                                 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
8209                                                 assert_eq!(msg.contents.flags & 2, 2); // temp disabled
8210                                         },
8211                                         _ => panic!("Unexpected event"),
8212                                 }
8213
8214                                 let events = nodes[0].node.get_and_clear_pending_events();
8215                                 assert_eq!(events.len(), 1);
8216                                 if let Event::PaymentFailed { payment_hash, rejected_by_dest, .. } = events[0] {
8217                                         assert_eq!(payment_hash, payment_hash_3);
8218                                         assert!(!rejected_by_dest);
8219                                 } else { panic!("Unexpected event!"); }
8220                         },
8221                         _ => panic!("Unexpected event type!"),
8222                 };
8223
8224                 let (payment_preimage_4, payment_hash_4) = if test_ignore_second_cs {
8225                         // Try to route another payment backwards from 2 to make sure 1 holds off on responding
8226                         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[0]);
8227                         let route = nodes[2].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8228                         nodes[2].node.send_payment(route, payment_hash_4).unwrap();
8229                         check_added_monitors!(nodes[2], 1);
8230
8231                         send_event = SendEvent::from_event(nodes[2].node.get_and_clear_pending_msg_events().remove(0));
8232                         nodes[1].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8233                         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) {
8234                                 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
8235                         } else { panic!(); }
8236                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8237                         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8238                         (Some(payment_preimage_4), Some(payment_hash_4))
8239                 } else { (None, None) };
8240
8241                 // Restore monitor updating, ensuring we immediately get a fail-back update and a
8242                 // update_add update.
8243                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8244                 nodes[1].node.test_restore_channel_monitor();
8245                 check_added_monitors!(nodes[1], 2);
8246
8247                 let mut events_3 = nodes[1].node.get_and_clear_pending_msg_events();
8248                 if test_ignore_second_cs {
8249                         assert_eq!(events_3.len(), 3);
8250                 } else {
8251                         assert_eq!(events_3.len(), 2);
8252                 }
8253
8254                 // Note that the ordering of the events for different nodes is non-prescriptive, though the
8255                 // ordering of the two events that both go to nodes[2] have to stay in the same order.
8256                 let messages_a = match events_3.pop().unwrap() {
8257                         MessageSendEvent::UpdateHTLCs { node_id, mut updates } => {
8258                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8259                                 assert!(updates.update_fulfill_htlcs.is_empty());
8260                                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8261                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8262                                 assert!(updates.update_add_htlcs.is_empty());
8263                                 assert!(updates.update_fee.is_none());
8264                                 (updates.update_fail_htlcs.remove(0), updates.commitment_signed)
8265                         },
8266                         _ => panic!("Unexpected event type!"),
8267                 };
8268                 let raa = if test_ignore_second_cs {
8269                         match events_3.remove(1) {
8270                                 MessageSendEvent::SendRevokeAndACK { node_id, msg } => {
8271                                         assert_eq!(node_id, nodes[2].node.get_our_node_id());
8272                                         Some(msg.clone())
8273                                 },
8274                                 _ => panic!("Unexpected event"),
8275                         }
8276                 } else { None };
8277                 let send_event_b = SendEvent::from_event(events_3.remove(0));
8278                 assert_eq!(send_event_b.node_id, nodes[2].node.get_our_node_id());
8279
8280                 // Now deliver the new messages...
8281
8282                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &messages_a.0).unwrap();
8283                 commitment_signed_dance!(nodes[0], nodes[1], messages_a.1, false);
8284                 let events_4 = nodes[0].node.get_and_clear_pending_events();
8285                 assert_eq!(events_4.len(), 1);
8286                 if let Event::PaymentFailed { payment_hash, rejected_by_dest, .. } = events_4[0] {
8287                         assert_eq!(payment_hash, payment_hash_1);
8288                         assert!(rejected_by_dest);
8289                 } else { panic!("Unexpected event!"); }
8290
8291                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event_b.msgs[0]).unwrap();
8292                 if test_ignore_second_cs {
8293                         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event_b.commitment_msg).unwrap();
8294                         check_added_monitors!(nodes[2], 1);
8295                         let bs_revoke_and_ack = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8296                         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa.unwrap()).unwrap();
8297                         check_added_monitors!(nodes[2], 1);
8298                         let bs_cs = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8299                         assert!(bs_cs.update_add_htlcs.is_empty());
8300                         assert!(bs_cs.update_fail_htlcs.is_empty());
8301                         assert!(bs_cs.update_fail_malformed_htlcs.is_empty());
8302                         assert!(bs_cs.update_fulfill_htlcs.is_empty());
8303                         assert!(bs_cs.update_fee.is_none());
8304
8305                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
8306                         check_added_monitors!(nodes[1], 1);
8307                         let as_cs = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
8308                         assert!(as_cs.update_add_htlcs.is_empty());
8309                         assert!(as_cs.update_fail_htlcs.is_empty());
8310                         assert!(as_cs.update_fail_malformed_htlcs.is_empty());
8311                         assert!(as_cs.update_fulfill_htlcs.is_empty());
8312                         assert!(as_cs.update_fee.is_none());
8313
8314                         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_cs.commitment_signed).unwrap();
8315                         check_added_monitors!(nodes[1], 1);
8316                         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
8317
8318                         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_cs.commitment_signed).unwrap();
8319                         check_added_monitors!(nodes[2], 1);
8320                         let bs_second_raa = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8321
8322                         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
8323                         check_added_monitors!(nodes[2], 1);
8324                         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
8325
8326                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_second_raa).unwrap();
8327                         check_added_monitors!(nodes[1], 1);
8328                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8329                 } else {
8330                         commitment_signed_dance!(nodes[2], nodes[1], send_event_b.commitment_msg, false);
8331                 }
8332
8333                 let events_5 = nodes[2].node.get_and_clear_pending_events();
8334                 assert_eq!(events_5.len(), 1);
8335                 match events_5[0] {
8336                         Event::PendingHTLCsForwardable { .. } => { },
8337                         _ => panic!("Unexpected event"),
8338                 };
8339
8340                 nodes[2].node.channel_state.lock().unwrap().next_forward = Instant::now();
8341                 nodes[2].node.process_pending_htlc_forwards();
8342
8343                 let events_6 = nodes[2].node.get_and_clear_pending_events();
8344                 assert_eq!(events_6.len(), 1);
8345                 match events_6[0] {
8346                         Event::PaymentReceived { payment_hash, .. } => { assert_eq!(payment_hash, payment_hash_2); },
8347                         _ => panic!("Unexpected event"),
8348                 };
8349
8350                 if test_ignore_second_cs {
8351                         let events_7 = nodes[1].node.get_and_clear_pending_events();
8352                         assert_eq!(events_7.len(), 1);
8353                         match events_7[0] {
8354                                 Event::PendingHTLCsForwardable { .. } => { },
8355                                 _ => panic!("Unexpected event"),
8356                         };
8357
8358                         nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8359                         nodes[1].node.process_pending_htlc_forwards();
8360                         check_added_monitors!(nodes[1], 1);
8361
8362                         send_event = SendEvent::from_node(&nodes[1]);
8363                         assert_eq!(send_event.node_id, nodes[0].node.get_our_node_id());
8364                         assert_eq!(send_event.msgs.len(), 1);
8365                         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8366                         commitment_signed_dance!(nodes[0], nodes[1], send_event.commitment_msg, false);
8367
8368                         let events_8 = nodes[0].node.get_and_clear_pending_events();
8369                         assert_eq!(events_8.len(), 1);
8370                         match events_8[0] {
8371                                 Event::PendingHTLCsForwardable { .. } => { },
8372                                 _ => panic!("Unexpected event"),
8373                         };
8374
8375                         nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
8376                         nodes[0].node.process_pending_htlc_forwards();
8377
8378                         let events_9 = nodes[0].node.get_and_clear_pending_events();
8379                         assert_eq!(events_9.len(), 1);
8380                         match events_9[0] {
8381                                 Event::PaymentReceived { payment_hash, .. } => assert_eq!(payment_hash, payment_hash_4.unwrap()),
8382                                 _ => panic!("Unexpected event"),
8383                         };
8384                         claim_payment(&nodes[2], &[&nodes[1], &nodes[0]], payment_preimage_4.unwrap());
8385                 }
8386
8387                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
8388         }
8389
8390         #[test]
8391         fn test_monitor_update_fail_raa() {
8392                 do_test_monitor_update_fail_raa(false);
8393                 do_test_monitor_update_fail_raa(true);
8394         }
8395
8396         #[test]
8397         fn test_monitor_update_fail_reestablish() {
8398                 // Simple test for message retransmission after monitor update failure on
8399                 // channel_reestablish generating a monitor update (which comes from freeing holding cell
8400                 // HTLCs).
8401                 let mut nodes = create_network(3);
8402                 create_announced_chan_between_nodes(&nodes, 0, 1);
8403                 create_announced_chan_between_nodes(&nodes, 1, 2);
8404
8405                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
8406
8407                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8408                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8409
8410                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
8411                 check_added_monitors!(nodes[2], 1);
8412                 let mut updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8413                 assert!(updates.update_add_htlcs.is_empty());
8414                 assert!(updates.update_fail_htlcs.is_empty());
8415                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8416                 assert!(updates.update_fee.is_none());
8417                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8418                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8419                 check_added_monitors!(nodes[1], 1);
8420                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8421                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
8422
8423                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8424                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8425                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8426
8427                 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
8428                 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8429
8430                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
8431
8432                 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() {
8433                         assert_eq!(err, "Failed to update ChannelMonitor");
8434                 } else { panic!(); }
8435                 check_added_monitors!(nodes[1], 1);
8436
8437                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8438                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8439
8440                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8441                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8442
8443                 assert!(as_reestablish == get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()));
8444                 assert!(bs_reestablish == get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id()));
8445
8446                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
8447
8448                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish).unwrap();
8449                 check_added_monitors!(nodes[1], 0);
8450                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8451
8452                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8453                 nodes[1].node.test_restore_channel_monitor();
8454                 check_added_monitors!(nodes[1], 1);
8455
8456                 updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8457                 assert!(updates.update_add_htlcs.is_empty());
8458                 assert!(updates.update_fail_htlcs.is_empty());
8459                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8460                 assert!(updates.update_fee.is_none());
8461                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8462                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8463                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
8464
8465                 let events = nodes[0].node.get_and_clear_pending_events();
8466                 assert_eq!(events.len(), 1);
8467                 match events[0] {
8468                         Event::PaymentSent { payment_preimage, .. } => assert_eq!(payment_preimage, our_payment_preimage),
8469                         _ => panic!("Unexpected event"),
8470                 }
8471         }
8472
8473         #[test]
8474         fn test_invalid_channel_announcement() {
8475                 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
8476                 let secp_ctx = Secp256k1::new();
8477                 let nodes = create_network(2);
8478
8479                 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1]);
8480
8481                 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8482                 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
8483                 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
8484                 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
8485
8486                 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 } );
8487
8488                 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
8489                 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
8490
8491                 let as_network_key = nodes[0].node.get_our_node_id();
8492                 let bs_network_key = nodes[1].node.get_our_node_id();
8493
8494                 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
8495
8496                 let mut chan_announcement;
8497
8498                 macro_rules! dummy_unsigned_msg {
8499                         () => {
8500                                 msgs::UnsignedChannelAnnouncement {
8501                                         features: msgs::GlobalFeatures::new(),
8502                                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
8503                                         short_channel_id: as_chan.get_short_channel_id().unwrap(),
8504                                         node_id_1: if were_node_one { as_network_key } else { bs_network_key },
8505                                         node_id_2: if were_node_one { bs_network_key } else { as_network_key },
8506                                         bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
8507                                         bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
8508                                         excess_data: Vec::new(),
8509                                 };
8510                         }
8511                 }
8512
8513                 macro_rules! sign_msg {
8514                         ($unsigned_msg: expr) => {
8515                                 let msghash = Message::from_slice(&Sha256dHash::from_data(&$unsigned_msg.encode()[..])[..]).unwrap();
8516                                 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
8517                                 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
8518                                 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].node.our_network_key);
8519                                 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].node.our_network_key);
8520                                 chan_announcement = msgs::ChannelAnnouncement {
8521                                         node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
8522                                         node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
8523                                         bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
8524                                         bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
8525                                         contents: $unsigned_msg
8526                                 }
8527                         }
8528                 }
8529
8530                 let unsigned_msg = dummy_unsigned_msg!();
8531                 sign_msg!(unsigned_msg);
8532                 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
8533                 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 } );
8534
8535                 // Configured with Network::Testnet
8536                 let mut unsigned_msg = dummy_unsigned_msg!();
8537                 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
8538                 sign_msg!(unsigned_msg);
8539                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
8540
8541                 let mut unsigned_msg = dummy_unsigned_msg!();
8542                 unsigned_msg.chain_hash = Sha256dHash::from_data(&[1,2,3,4,5,6,7,8,9]);
8543                 sign_msg!(unsigned_msg);
8544                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
8545         }
8546
8547         struct VecWriter(Vec<u8>);
8548         impl Writer for VecWriter {
8549                 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
8550                         self.0.extend_from_slice(buf);
8551                         Ok(())
8552                 }
8553                 fn size_hint(&mut self, size: usize) {
8554                         self.0.reserve_exact(size);
8555                 }
8556         }
8557
8558         #[test]
8559         fn test_no_txn_manager_serialize_deserialize() {
8560                 let mut nodes = create_network(2);
8561
8562                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
8563
8564                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8565
8566                 let nodes_0_serialized = nodes[0].node.encode();
8567                 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8568                 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8569
8570                 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())));
8571                 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8572                 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8573                 assert!(chan_0_monitor_read.is_empty());
8574
8575                 let mut nodes_0_read = &nodes_0_serialized[..];
8576                 let config = UserConfig::new();
8577                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8578                 let (_, nodes_0_deserialized) = {
8579                         let mut channel_monitors = HashMap::new();
8580                         channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8581                         <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8582                                 default_config: config,
8583                                 keys_manager,
8584                                 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8585                                 monitor: nodes[0].chan_monitor.clone(),
8586                                 chain_monitor: nodes[0].chain_monitor.clone(),
8587                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8588                                 logger: Arc::new(test_utils::TestLogger::new()),
8589                                 channel_monitors: &channel_monitors,
8590                         }).unwrap()
8591                 };
8592                 assert!(nodes_0_read.is_empty());
8593
8594                 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8595                 nodes[0].node = Arc::new(nodes_0_deserialized);
8596                 let nodes_0_as_listener: Arc<ChainListener> = nodes[0].node.clone();
8597                 nodes[0].chain_monitor.register_listener(Arc::downgrade(&nodes_0_as_listener));
8598                 assert_eq!(nodes[0].node.list_channels().len(), 1);
8599                 check_added_monitors!(nodes[0], 1);
8600
8601                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8602                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
8603                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8604                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
8605
8606                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
8607                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8608                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
8609                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8610
8611                 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8612                 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8613                 for node in nodes.iter() {
8614                         assert!(node.router.handle_channel_announcement(&announcement).unwrap());
8615                         node.router.handle_channel_update(&as_update).unwrap();
8616                         node.router.handle_channel_update(&bs_update).unwrap();
8617                 }
8618
8619                 send_payment(&nodes[0], &[&nodes[1]], 1000000);
8620         }
8621
8622         #[test]
8623         fn test_simple_manager_serialize_deserialize() {
8624                 let mut nodes = create_network(2);
8625                 create_announced_chan_between_nodes(&nodes, 0, 1);
8626
8627                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8628                 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8629
8630                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8631
8632                 let nodes_0_serialized = nodes[0].node.encode();
8633                 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8634                 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8635
8636                 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())));
8637                 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8638                 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8639                 assert!(chan_0_monitor_read.is_empty());
8640
8641                 let mut nodes_0_read = &nodes_0_serialized[..];
8642                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8643                 let (_, nodes_0_deserialized) = {
8644                         let mut channel_monitors = HashMap::new();
8645                         channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8646                         <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8647                                 default_config: UserConfig::new(),
8648                                 keys_manager,
8649                                 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8650                                 monitor: nodes[0].chan_monitor.clone(),
8651                                 chain_monitor: nodes[0].chain_monitor.clone(),
8652                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8653                                 logger: Arc::new(test_utils::TestLogger::new()),
8654                                 channel_monitors: &channel_monitors,
8655                         }).unwrap()
8656                 };
8657                 assert!(nodes_0_read.is_empty());
8658
8659                 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8660                 nodes[0].node = Arc::new(nodes_0_deserialized);
8661                 check_added_monitors!(nodes[0], 1);
8662
8663                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8664
8665                 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
8666                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
8667         }
8668
8669         #[test]
8670         fn test_manager_serialize_deserialize_inconsistent_monitor() {
8671                 // Test deserializing a ChannelManager with a out-of-date ChannelMonitor
8672                 let mut nodes = create_network(4);
8673                 create_announced_chan_between_nodes(&nodes, 0, 1);
8674                 create_announced_chan_between_nodes(&nodes, 2, 0);
8675                 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3);
8676
8677                 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
8678
8679                 // Serialize the ChannelManager here, but the monitor we keep up-to-date
8680                 let nodes_0_serialized = nodes[0].node.encode();
8681
8682                 route_payment(&nodes[0], &[&nodes[3]], 1000000);
8683                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8684                 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8685                 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8686
8687                 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
8688                 // nodes[3])
8689                 let mut node_0_monitors_serialized = Vec::new();
8690                 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
8691                         let mut writer = VecWriter(Vec::new());
8692                         monitor.1.write_for_disk(&mut writer).unwrap();
8693                         node_0_monitors_serialized.push(writer.0);
8694                 }
8695
8696                 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())));
8697                 let mut node_0_monitors = Vec::new();
8698                 for serialized in node_0_monitors_serialized.iter() {
8699                         let mut read = &serialized[..];
8700                         let (_, monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
8701                         assert!(read.is_empty());
8702                         node_0_monitors.push(monitor);
8703                 }
8704
8705                 let mut nodes_0_read = &nodes_0_serialized[..];
8706                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8707                 let (_, nodes_0_deserialized) = <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8708                         default_config: UserConfig::new(),
8709                         keys_manager,
8710                         fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8711                         monitor: nodes[0].chan_monitor.clone(),
8712                         chain_monitor: nodes[0].chain_monitor.clone(),
8713                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8714                         logger: Arc::new(test_utils::TestLogger::new()),
8715                         channel_monitors: &node_0_monitors.iter().map(|monitor| { (monitor.get_funding_txo().unwrap(), monitor) }).collect(),
8716                 }).unwrap();
8717                 assert!(nodes_0_read.is_empty());
8718
8719                 { // Channel close should result in a commitment tx and an HTLC tx
8720                         let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8721                         assert_eq!(txn.len(), 2);
8722                         assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
8723                         assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
8724                 }
8725
8726                 for monitor in node_0_monitors.drain(..) {
8727                         assert!(nodes[0].chan_monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor).is_ok());
8728                         check_added_monitors!(nodes[0], 1);
8729                 }
8730                 nodes[0].node = Arc::new(nodes_0_deserialized);
8731
8732                 // nodes[1] and nodes[2] have no lost state with nodes[0]...
8733                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8734                 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8735                 //... and we can even still claim the payment!
8736                 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
8737
8738                 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id());
8739                 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8740                 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id());
8741                 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) {
8742                         assert_eq!(msg.channel_id, channel_id);
8743                 } else { panic!("Unexpected result"); }
8744         }
8745
8746         macro_rules! check_spendable_outputs {
8747                 ($node: expr, $der_idx: expr) => {
8748                         {
8749                                 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
8750                                 let mut txn = Vec::new();
8751                                 for event in events {
8752                                         match event {
8753                                                 Event::SpendableOutputs { ref outputs } => {
8754                                                         for outp in outputs {
8755                                                                 match *outp {
8756                                                                         SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
8757                                                                                 let input = TxIn {
8758                                                                                         previous_output: outpoint.clone(),
8759                                                                                         script_sig: Script::new(),
8760                                                                                         sequence: 0,
8761                                                                                         witness: Vec::new(),
8762                                                                                 };
8763                                                                                 let outp = TxOut {
8764                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8765                                                                                         value: output.value,
8766                                                                                 };
8767                                                                                 let mut spend_tx = Transaction {
8768                                                                                         version: 2,
8769                                                                                         lock_time: 0,
8770                                                                                         input: vec![input],
8771                                                                                         output: vec![outp],
8772                                                                                 };
8773                                                                                 let secp_ctx = Secp256k1::new();
8774                                                                                 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
8775                                                                                 let witness_script = Address::p2pkh(&remotepubkey, Network::Testnet).script_pubkey();
8776                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8777                                                                                 let remotesig = secp_ctx.sign(&sighash, key);
8778                                                                                 spend_tx.input[0].witness.push(remotesig.serialize_der(&secp_ctx).to_vec());
8779                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8780                                                                                 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
8781                                                                                 txn.push(spend_tx);
8782                                                                         },
8783                                                                         SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
8784                                                                                 let input = TxIn {
8785                                                                                         previous_output: outpoint.clone(),
8786                                                                                         script_sig: Script::new(),
8787                                                                                         sequence: *to_self_delay as u32,
8788                                                                                         witness: Vec::new(),
8789                                                                                 };
8790                                                                                 let outp = TxOut {
8791                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8792                                                                                         value: output.value,
8793                                                                                 };
8794                                                                                 let mut spend_tx = Transaction {
8795                                                                                         version: 2,
8796                                                                                         lock_time: 0,
8797                                                                                         input: vec![input],
8798                                                                                         output: vec![outp],
8799                                                                                 };
8800                                                                                 let secp_ctx = Secp256k1::new();
8801                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
8802                                                                                 let local_delaysig = secp_ctx.sign(&sighash, key);
8803                                                                                 spend_tx.input[0].witness.push(local_delaysig.serialize_der(&secp_ctx).to_vec());
8804                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8805                                                                                 spend_tx.input[0].witness.push(vec!(0));
8806                                                                                 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
8807                                                                                 txn.push(spend_tx);
8808                                                                         },
8809                                                                         SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
8810                                                                                 let secp_ctx = Secp256k1::new();
8811                                                                                 let input = TxIn {
8812                                                                                         previous_output: outpoint.clone(),
8813                                                                                         script_sig: Script::new(),
8814                                                                                         sequence: 0,
8815                                                                                         witness: Vec::new(),
8816                                                                                 };
8817                                                                                 let outp = TxOut {
8818                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8819                                                                                         value: output.value,
8820                                                                                 };
8821                                                                                 let mut spend_tx = Transaction {
8822                                                                                         version: 2,
8823                                                                                         lock_time: 0,
8824                                                                                         input: vec![input],
8825                                                                                         output: vec![outp.clone()],
8826                                                                                 };
8827                                                                                 let secret = {
8828                                                                                         match ExtendedPrivKey::new_master(&secp_ctx, Network::Testnet, &$node.node_seed) {
8829                                                                                                 Ok(master_key) => {
8830                                                                                                         match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx)) {
8831                                                                                                                 Ok(key) => key,
8832                                                                                                                 Err(_) => panic!("Your RNG is busted"),
8833                                                                                                         }
8834                                                                                                 }
8835                                                                                                 Err(_) => panic!("Your rng is busted"),
8836                                                                                         }
8837                                                                                 };
8838                                                                                 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
8839                                                                                 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
8840                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8841                                                                                 let sig = secp_ctx.sign(&sighash, &secret.secret_key);
8842                                                                                 spend_tx.input[0].witness.push(sig.serialize_der(&secp_ctx).to_vec());
8843                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8844                                                                                 spend_tx.input[0].witness.push(pubkey.serialize().to_vec());
8845                                                                                 txn.push(spend_tx);
8846                                                                         },
8847                                                                 }
8848                                                         }
8849                                                 },
8850                                                 _ => panic!("Unexpected event"),
8851                                         };
8852                                 }
8853                                 txn
8854                         }
8855                 }
8856         }
8857
8858         #[test]
8859         fn test_claim_sizeable_push_msat() {
8860                 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
8861                 let nodes = create_network(2);
8862
8863                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8864                 nodes[1].node.force_close_channel(&chan.2);
8865                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8866                 match events[0] {
8867                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8868                         _ => panic!("Unexpected event"),
8869                 }
8870                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8871                 assert_eq!(node_txn.len(), 1);
8872                 check_spends!(node_txn[0], chan.3.clone());
8873                 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
8874
8875                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8876                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8877                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8878                 assert_eq!(spend_txn.len(), 1);
8879                 check_spends!(spend_txn[0], node_txn[0].clone());
8880         }
8881
8882         #[test]
8883         fn test_claim_on_remote_sizeable_push_msat() {
8884                 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8885                 // to_remote output is encumbered by a P2WPKH
8886
8887                 let nodes = create_network(2);
8888
8889                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8890                 nodes[0].node.force_close_channel(&chan.2);
8891                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8892                 match events[0] {
8893                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8894                         _ => panic!("Unexpected event"),
8895                 }
8896                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8897                 assert_eq!(node_txn.len(), 1);
8898                 check_spends!(node_txn[0], chan.3.clone());
8899                 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
8900
8901                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8902                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8903                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8904                 match events[0] {
8905                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8906                         _ => panic!("Unexpected event"),
8907                 }
8908                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8909                 assert_eq!(spend_txn.len(), 2);
8910                 assert_eq!(spend_txn[0], spend_txn[1]);
8911                 check_spends!(spend_txn[0], node_txn[0].clone());
8912         }
8913
8914         #[test]
8915         fn test_claim_on_remote_revoked_sizeable_push_msat() {
8916                 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8917                 // to_remote output is encumbered by a P2WPKH
8918
8919                 let nodes = create_network(2);
8920
8921                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
8922                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8923                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
8924                 assert_eq!(revoked_local_txn[0].input.len(), 1);
8925                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8926
8927                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8928                 let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8929                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
8930                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8931                 match events[0] {
8932                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8933                         _ => panic!("Unexpected event"),
8934                 }
8935                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8936                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8937                 assert_eq!(spend_txn.len(), 4);
8938                 assert_eq!(spend_txn[0], spend_txn[2]); // to_remote output on revoked remote commitment_tx
8939                 check_spends!(spend_txn[0], revoked_local_txn[0].clone());
8940                 assert_eq!(spend_txn[1], spend_txn[3]); // to_local output on local commitment tx
8941                 check_spends!(spend_txn[1], node_txn[0].clone());
8942         }
8943
8944         #[test]
8945         fn test_static_spendable_outputs_preimage_tx() {
8946                 let nodes = create_network(2);
8947
8948                 // Create some initial channels
8949                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8950
8951                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8952
8953                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8954                 assert_eq!(commitment_tx[0].input.len(), 1);
8955                 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
8956
8957                 // Settle A's commitment tx on B's chain
8958                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8959                 assert!(nodes[1].node.claim_funds(payment_preimage));
8960                 check_added_monitors!(nodes[1], 1);
8961                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
8962                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8963                 match events[0] {
8964                         MessageSendEvent::UpdateHTLCs { .. } => {},
8965                         _ => panic!("Unexpected event"),
8966                 }
8967                 match events[1] {
8968                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8969                         _ => panic!("Unexepected event"),
8970                 }
8971
8972                 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
8973                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 1 (local commitment tx), ChannelMonitor: 2 (1 preimage tx) * 2 (block-rescan)
8974                 check_spends!(node_txn[0], commitment_tx[0].clone());
8975                 assert_eq!(node_txn[0], node_txn[2]);
8976                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8977                 check_spends!(node_txn[1], chan_1.3.clone());
8978
8979                 let spend_txn = check_spendable_outputs!(nodes[1], 1); // , 0, 0, 1, 1);
8980                 assert_eq!(spend_txn.len(), 2);
8981                 assert_eq!(spend_txn[0], spend_txn[1]);
8982                 check_spends!(spend_txn[0], node_txn[0].clone());
8983         }
8984
8985         #[test]
8986         fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
8987                 let nodes = create_network(2);
8988
8989                 // Create some initial channels
8990                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8991
8992                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8993                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
8994                 assert_eq!(revoked_local_txn[0].input.len(), 1);
8995                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
8996
8997                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8998
8999                 let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9000                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9001                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9002                 match events[0] {
9003                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9004                         _ => panic!("Unexpected event"),
9005                 }
9006                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9007                 assert_eq!(node_txn.len(), 3);
9008                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]);
9009                 assert_eq!(node_txn[0].input.len(), 2);
9010                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
9011
9012                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9013                 assert_eq!(spend_txn.len(), 2);
9014                 assert_eq!(spend_txn[0], spend_txn[1]);
9015                 check_spends!(spend_txn[0], node_txn[0].clone());
9016         }
9017
9018         #[test]
9019         fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
9020                 let nodes = create_network(2);
9021
9022                 // Create some initial channels
9023                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9024
9025                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9026                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9027                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9028                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9029
9030                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9031
9032                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9033                 // A will generate HTLC-Timeout from revoked commitment tx
9034                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9035                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9036                 match events[0] {
9037                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9038                         _ => panic!("Unexpected event"),
9039                 }
9040                 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9041                 assert_eq!(revoked_htlc_txn.len(), 3);
9042                 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
9043                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
9044                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9045                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
9046                 check_spends!(revoked_htlc_txn[1], chan_1.3.clone());
9047
9048                 // B will generate justice tx from A's revoked commitment/HTLC tx
9049                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
9050                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9051                 match events[0] {
9052                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9053                         _ => panic!("Unexpected event"),
9054                 }
9055
9056                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9057                 assert_eq!(node_txn.len(), 4);
9058                 assert_eq!(node_txn[3].input.len(), 1);
9059                 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
9060
9061                 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
9062                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9063                 assert_eq!(spend_txn.len(), 3);
9064                 assert_eq!(spend_txn[0], spend_txn[1]);
9065                 check_spends!(spend_txn[0], node_txn[0].clone());
9066                 check_spends!(spend_txn[2], node_txn[3].clone());
9067         }
9068
9069         #[test]
9070         fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
9071                 let nodes = create_network(2);
9072
9073                 // Create some initial channels
9074                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9075
9076                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9077                 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9078                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9079                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9080
9081                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9082
9083                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9084                 // B will generate HTLC-Success from revoked commitment tx
9085                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9086                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9087                 match events[0] {
9088                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9089                         _ => panic!("Unexpected event"),
9090                 }
9091                 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9092
9093                 assert_eq!(revoked_htlc_txn.len(), 3);
9094                 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
9095                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
9096                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9097                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
9098
9099                 // A will generate justice tx from B's revoked commitment/HTLC tx
9100                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
9101                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9102                 match events[0] {
9103                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9104                         _ => panic!("Unexpected event"),
9105                 }
9106
9107                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9108                 assert_eq!(node_txn.len(), 4);
9109                 assert_eq!(node_txn[3].input.len(), 1);
9110                 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
9111
9112                 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
9113                 let spend_txn = check_spendable_outputs!(nodes[0], 1);
9114                 assert_eq!(spend_txn.len(), 5);
9115                 assert_eq!(spend_txn[0], spend_txn[2]);
9116                 assert_eq!(spend_txn[1], spend_txn[3]);
9117                 check_spends!(spend_txn[0], revoked_local_txn[0].clone()); // spending to_remote output from revoked local tx
9118                 check_spends!(spend_txn[1], node_txn[2].clone()); // spending justice tx output from revoked local tx htlc received output
9119                 check_spends!(spend_txn[4], node_txn[3].clone()); // spending justice tx output on htlc success tx
9120         }
9121
9122         #[test]
9123         fn test_onchain_to_onchain_claim() {
9124                 // Test that in case of channel closure, we detect the state of output thanks to
9125                 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
9126                 // First, have C claim an HTLC against its own latest commitment transaction.
9127                 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
9128                 // channel.
9129                 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
9130                 // gets broadcast.
9131
9132                 let nodes = create_network(3);
9133
9134                 // Create some initial channels
9135                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9136                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
9137
9138                 // Rebalance the network a bit by relaying one payment through all the channels ...
9139                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
9140                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
9141
9142                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
9143                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9144                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
9145                 check_spends!(commitment_tx[0], chan_2.3.clone());
9146                 nodes[2].node.claim_funds(payment_preimage);
9147                 check_added_monitors!(nodes[2], 1);
9148                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9149                 assert!(updates.update_add_htlcs.is_empty());
9150                 assert!(updates.update_fail_htlcs.is_empty());
9151                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
9152                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9153
9154                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
9155                 let events = nodes[2].node.get_and_clear_pending_msg_events();
9156                 assert_eq!(events.len(), 1);
9157                 match events[0] {
9158                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9159                         _ => panic!("Unexpected event"),
9160                 }
9161
9162                 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
9163                 assert_eq!(c_txn.len(), 3);
9164                 assert_eq!(c_txn[0], c_txn[2]);
9165                 assert_eq!(commitment_tx[0], c_txn[1]);
9166                 check_spends!(c_txn[1], chan_2.3.clone());
9167                 check_spends!(c_txn[2], c_txn[1].clone());
9168                 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
9169                 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9170                 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
9171                 assert_eq!(c_txn[0].lock_time, 0); // Success tx
9172
9173                 // 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
9174                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
9175                 {
9176                         let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9177                         assert_eq!(b_txn.len(), 4);
9178                         assert_eq!(b_txn[0], b_txn[3]);
9179                         check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
9180                         check_spends!(b_txn[2], b_txn[1].clone()); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
9181                         assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9182                         assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
9183                         assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
9184                         check_spends!(b_txn[0], c_txn[1].clone()); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
9185                         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9186                         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
9187                         assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
9188                         b_txn.clear();
9189                 }
9190                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
9191                 check_added_monitors!(nodes[1], 1);
9192                 match msg_events[0] {
9193                         MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
9194                         _ => panic!("Unexpected event"),
9195                 }
9196                 match msg_events[1] {
9197                         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, .. } } => {
9198                                 assert!(update_add_htlcs.is_empty());
9199                                 assert!(update_fail_htlcs.is_empty());
9200                                 assert_eq!(update_fulfill_htlcs.len(), 1);
9201                                 assert!(update_fail_malformed_htlcs.is_empty());
9202                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
9203                         },
9204                         _ => panic!("Unexpected event"),
9205                 };
9206                 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
9207                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9208                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
9209                 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9210                 assert_eq!(b_txn.len(), 3);
9211                 check_spends!(b_txn[1], chan_1.3); // Local commitment tx, issued by ChannelManager
9212                 assert_eq!(b_txn[0], b_txn[2]); // HTLC-Success tx, issued by ChannelMonitor, * 2 due to block rescan
9213                 check_spends!(b_txn[0], commitment_tx[0].clone());
9214                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9215                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
9216                 assert_eq!(b_txn[2].lock_time, 0); // Success tx
9217                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
9218                 match msg_events[0] {
9219                         MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
9220                         _ => panic!("Unexpected event"),
9221                 }
9222         }
9223
9224         #[test]
9225         fn test_duplicate_payment_hash_one_failure_one_success() {
9226                 // Topology : A --> B --> C
9227                 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
9228                 let mut nodes = create_network(3);
9229
9230                 create_announced_chan_between_nodes(&nodes, 0, 1);
9231                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
9232
9233                 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
9234                 *nodes[0].network_payment_count.borrow_mut() -= 1;
9235                 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
9236
9237                 let commitment_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
9238                 assert_eq!(commitment_txn[0].input.len(), 1);
9239                 check_spends!(commitment_txn[0], chan_2.3.clone());
9240
9241                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9242                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
9243                 let htlc_timeout_tx;
9244                 { // Extract one of the two HTLC-Timeout transaction
9245                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9246                         assert_eq!(node_txn.len(), 7);
9247                         assert_eq!(node_txn[0], node_txn[5]);
9248                         assert_eq!(node_txn[1], node_txn[6]);
9249                         check_spends!(node_txn[0], commitment_txn[0].clone());
9250                         assert_eq!(node_txn[0].input.len(), 1);
9251                         check_spends!(node_txn[1], commitment_txn[0].clone());
9252                         assert_eq!(node_txn[1].input.len(), 1);
9253                         assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
9254                         check_spends!(node_txn[2], chan_2.3.clone());
9255                         check_spends!(node_txn[3], node_txn[2].clone());
9256                         check_spends!(node_txn[4], node_txn[2].clone());
9257                         htlc_timeout_tx = node_txn[1].clone();
9258                 }
9259
9260                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9261                 match events[0] {
9262                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9263                         _ => panic!("Unexepected event"),
9264                 }
9265
9266                 nodes[2].node.claim_funds(our_payment_preimage);
9267                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
9268                 check_added_monitors!(nodes[2], 2);
9269                 let events = nodes[2].node.get_and_clear_pending_msg_events();
9270                 match events[0] {
9271                         MessageSendEvent::UpdateHTLCs { .. } => {},
9272                         _ => panic!("Unexpected event"),
9273                 }
9274                 match events[1] {
9275                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9276                         _ => panic!("Unexepected event"),
9277                 }
9278                 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9279                 assert_eq!(htlc_success_txn.len(), 5);
9280                 check_spends!(htlc_success_txn[2], chan_2.3.clone());
9281                 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
9282                 assert_eq!(htlc_success_txn[0].input.len(), 1);
9283                 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9284                 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
9285                 assert_eq!(htlc_success_txn[1].input.len(), 1);
9286                 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9287                 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
9288                 check_spends!(htlc_success_txn[0], commitment_txn[0].clone());
9289                 check_spends!(htlc_success_txn[1], commitment_txn[0].clone());
9290
9291                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
9292                 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9293                 assert!(htlc_updates.update_add_htlcs.is_empty());
9294                 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
9295                 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
9296                 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
9297                 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
9298                 check_added_monitors!(nodes[1], 1);
9299
9300                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]).unwrap();
9301                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9302                 {
9303                         commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
9304                         let events = nodes[0].node.get_and_clear_pending_msg_events();
9305                         assert_eq!(events.len(), 1);
9306                         match events[0] {
9307                                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
9308                                 },
9309                                 _ => { panic!("Unexpected event"); }
9310                         }
9311                 }
9312                 let events = nodes[0].node.get_and_clear_pending_events();
9313                 match events[0] {
9314                         Event::PaymentFailed { ref payment_hash, .. } => {
9315                                 assert_eq!(*payment_hash, duplicate_payment_hash);
9316                         }
9317                         _ => panic!("Unexpected event"),
9318                 }
9319
9320                 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
9321                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
9322                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9323                 assert!(updates.update_add_htlcs.is_empty());
9324                 assert!(updates.update_fail_htlcs.is_empty());
9325                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
9326                 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
9327                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9328                 check_added_monitors!(nodes[1], 1);
9329
9330                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
9331                 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
9332
9333                 let events = nodes[0].node.get_and_clear_pending_events();
9334                 match events[0] {
9335                         Event::PaymentSent { ref payment_preimage } => {
9336                                 assert_eq!(*payment_preimage, our_payment_preimage);
9337                         }
9338                         _ => panic!("Unexpected event"),
9339                 }
9340         }
9341
9342         #[test]
9343         fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
9344                 let nodes = create_network(2);
9345
9346                 // Create some initial channels
9347                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9348
9349                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
9350                 let local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9351                 assert_eq!(local_txn[0].input.len(), 1);
9352                 check_spends!(local_txn[0], chan_1.3.clone());
9353
9354                 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
9355                 nodes[1].node.claim_funds(payment_preimage);
9356                 check_added_monitors!(nodes[1], 1);
9357                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9358                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
9359                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9360                 match events[0] {
9361                         MessageSendEvent::UpdateHTLCs { .. } => {},
9362                         _ => panic!("Unexpected event"),
9363                 }
9364                 match events[1] {
9365                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9366                         _ => panic!("Unexepected event"),
9367                 }
9368                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9369                 assert_eq!(node_txn[0].input.len(), 1);
9370                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9371                 check_spends!(node_txn[0], local_txn[0].clone());
9372
9373                 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
9374                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9375                 assert_eq!(spend_txn.len(), 2);
9376                 check_spends!(spend_txn[0], node_txn[0].clone());
9377                 check_spends!(spend_txn[1], node_txn[2].clone());
9378         }
9379
9380         #[test]
9381         fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
9382                 let nodes = create_network(2);
9383
9384                 // Create some initial channels
9385                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9386
9387                 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
9388                 let local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9389                 assert_eq!(local_txn[0].input.len(), 1);
9390                 check_spends!(local_txn[0], chan_1.3.clone());
9391
9392                 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
9393                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9394                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
9395                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9396                 match events[0] {
9397                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9398                         _ => panic!("Unexepected event"),
9399                 }
9400                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9401                 assert_eq!(node_txn[0].input.len(), 1);
9402                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9403                 check_spends!(node_txn[0], local_txn[0].clone());
9404
9405                 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
9406                 let spend_txn = check_spendable_outputs!(nodes[0], 1);
9407                 assert_eq!(spend_txn.len(), 8);
9408                 assert_eq!(spend_txn[0], spend_txn[2]);
9409                 assert_eq!(spend_txn[0], spend_txn[4]);
9410                 assert_eq!(spend_txn[0], spend_txn[6]);
9411                 assert_eq!(spend_txn[1], spend_txn[3]);
9412                 assert_eq!(spend_txn[1], spend_txn[5]);
9413                 assert_eq!(spend_txn[1], spend_txn[7]);
9414                 check_spends!(spend_txn[0], local_txn[0].clone());
9415                 check_spends!(spend_txn[1], node_txn[0].clone());
9416         }
9417
9418         #[test]
9419         fn test_static_output_closing_tx() {
9420                 let nodes = create_network(2);
9421
9422                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
9423
9424                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
9425                 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
9426
9427                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9428                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
9429                 let spend_txn = check_spendable_outputs!(nodes[0], 2);
9430                 assert_eq!(spend_txn.len(), 1);
9431                 check_spends!(spend_txn[0], closing_tx.clone());
9432
9433                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
9434                 let spend_txn = check_spendable_outputs!(nodes[1], 2);
9435                 assert_eq!(spend_txn.len(), 1);
9436                 check_spends!(spend_txn[0], closing_tx);
9437         }
9438
9439         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>)
9440                 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
9441                                         F2: FnMut(),
9442         {
9443                 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);
9444         }
9445
9446         // test_case
9447         // 0: node1 fail backward
9448         // 1: final node fail backward
9449         // 2: payment completed but the user reject the payment
9450         // 3: final node fail backward (but tamper onion payloads from node0)
9451         // 100: trigger error in the intermediate node and tamper returnning fail_htlc
9452         // 200: trigger error in the final node and tamper returnning fail_htlc
9453         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>)
9454                 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
9455                                         F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
9456                                         F3: FnMut(),
9457         {
9458                 use ln::msgs::HTLCFailChannelUpdate;
9459
9460                 // reset block height
9461                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9462                 for ix in 0..nodes.len() {
9463                         nodes[ix].chain_monitor.block_connected_checked(&header, 1, &Vec::new()[..], &[0; 0]);
9464                 }
9465
9466                 macro_rules! expect_event {
9467                         ($node: expr, $event_type: path) => {{
9468                                 let events = $node.node.get_and_clear_pending_events();
9469                                 assert_eq!(events.len(), 1);
9470                                 match events[0] {
9471                                         $event_type { .. } => {},
9472                                         _ => panic!("Unexpected event"),
9473                                 }
9474                         }}
9475                 }
9476
9477                 macro_rules! expect_htlc_forward {
9478                         ($node: expr) => {{
9479                                 expect_event!($node, Event::PendingHTLCsForwardable);
9480                                 $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
9481                                 $node.node.process_pending_htlc_forwards();
9482                         }}
9483                 }
9484
9485                 // 0 ~~> 2 send payment
9486                 nodes[0].node.send_payment(route.clone(), payment_hash.clone()).unwrap();
9487                 check_added_monitors!(nodes[0], 1);
9488                 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
9489                 // temper update_add (0 => 1)
9490                 let mut update_add_0 = update_0.update_add_htlcs[0].clone();
9491                 if test_case == 0 || test_case == 3 || test_case == 100 {
9492                         callback_msg(&mut update_add_0);
9493                         callback_node();
9494                 }
9495                 // 0 => 1 update_add & CS
9496                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0).unwrap();
9497                 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
9498
9499                 let update_1_0 = match test_case {
9500                         0|100 => { // intermediate node failure; fail backward to 0
9501                                 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9502                                 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));
9503                                 update_1_0
9504                         },
9505                         1|2|3|200 => { // final node failure; forwarding to 2
9506                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9507                                 // forwarding on 1
9508                                 if test_case != 200 {
9509                                         callback_node();
9510                                 }
9511                                 expect_htlc_forward!(&nodes[1]);
9512
9513                                 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
9514                                 check_added_monitors!(&nodes[1], 1);
9515                                 assert_eq!(update_1.update_add_htlcs.len(), 1);
9516                                 // tamper update_add (1 => 2)
9517                                 let mut update_add_1 = update_1.update_add_htlcs[0].clone();
9518                                 if test_case != 3 && test_case != 200 {
9519                                         callback_msg(&mut update_add_1);
9520                                 }
9521
9522                                 // 1 => 2
9523                                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1).unwrap();
9524                                 commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
9525
9526                                 if test_case == 2 || test_case == 200 {
9527                                         expect_htlc_forward!(&nodes[2]);
9528                                         expect_event!(&nodes[2], Event::PaymentReceived);
9529                                         callback_node();
9530                                 }
9531
9532                                 let update_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9533                                 if test_case == 2 || test_case == 200 {
9534                                         check_added_monitors!(&nodes[2], 1);
9535                                 }
9536                                 assert!(update_2_1.update_fail_htlcs.len() == 1);
9537
9538                                 let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
9539                                 if test_case == 200 {
9540                                         callback_fail(&mut fail_msg);
9541                                 }
9542
9543                                 // 2 => 1
9544                                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg).unwrap();
9545                                 commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true, true);
9546
9547                                 // backward fail on 1
9548                                 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9549                                 assert!(update_1_0.update_fail_htlcs.len() == 1);
9550                                 update_1_0
9551                         },
9552                         _ => unreachable!(),
9553                 };
9554
9555                 // 1 => 0 commitment_signed_dance
9556                 if update_1_0.update_fail_htlcs.len() > 0 {
9557                         let mut fail_msg = update_1_0.update_fail_htlcs[0].clone();
9558                         if test_case == 100 {
9559                                 callback_fail(&mut fail_msg);
9560                         }
9561                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg).unwrap();
9562                 } else {
9563                         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]).unwrap();
9564                 };
9565
9566                 commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
9567
9568                 let events = nodes[0].node.get_and_clear_pending_events();
9569                 assert_eq!(events.len(), 1);
9570                 if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code } = &events[0] {
9571                         assert_eq!(*rejected_by_dest, !expected_retryable);
9572                         assert_eq!(*error_code, expected_error_code);
9573                 } else {
9574                         panic!("Uexpected event");
9575                 }
9576
9577                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9578                 if expected_channel_update.is_some() {
9579                         assert_eq!(events.len(), 1);
9580                         match events[0] {
9581                                 MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
9582                                         match update {
9583                                                 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {
9584                                                         if let HTLCFailChannelUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
9585                                                                 panic!("channel_update not found!");
9586                                                         }
9587                                                 },
9588                                                 &HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
9589                                                         if let HTLCFailChannelUpdate::ChannelClosed { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
9590                                                                 assert!(*short_channel_id == *expected_short_channel_id);
9591                                                                 assert!(*is_permanent == *expected_is_permanent);
9592                                                         } else {
9593                                                                 panic!("Unexpected message event");
9594                                                         }
9595                                                 },
9596                                                 &HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
9597                                                         if let HTLCFailChannelUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
9598                                                                 assert!(*node_id == *expected_node_id);
9599                                                                 assert!(*is_permanent == *expected_is_permanent);
9600                                                         } else {
9601                                                                 panic!("Unexpected message event");
9602                                                         }
9603                                                 },
9604                                         }
9605                                 },
9606                                 _ => panic!("Unexpected message event"),
9607                         }
9608                 } else {
9609                         assert_eq!(events.len(), 0);
9610                 }
9611         }
9612
9613         impl msgs::ChannelUpdate {
9614                 fn dummy() -> msgs::ChannelUpdate {
9615                         use secp256k1::ffi::Signature as FFISignature;
9616                         use secp256k1::Signature;
9617                         msgs::ChannelUpdate {
9618                                 signature: Signature::from(FFISignature::new()),
9619                                 contents: msgs::UnsignedChannelUpdate {
9620                                         chain_hash: Sha256dHash::from_data(&vec![0u8][..]),
9621                                         short_channel_id: 0,
9622                                         timestamp: 0,
9623                                         flags: 0,
9624                                         cltv_expiry_delta: 0,
9625                                         htlc_minimum_msat: 0,
9626                                         fee_base_msat: 0,
9627                                         fee_proportional_millionths: 0,
9628                                         excess_data: vec![],
9629                                 }
9630                         }
9631                 }
9632         }
9633
9634         #[test]
9635         fn test_onion_failure() {
9636                 use ln::msgs::ChannelUpdate;
9637                 use ln::channelmanager::CLTV_FAR_FAR_AWAY;
9638                 use secp256k1;
9639
9640                 const BADONION: u16 = 0x8000;
9641                 const PERM: u16 = 0x4000;
9642                 const NODE: u16 = 0x2000;
9643                 const UPDATE: u16 = 0x1000;
9644
9645                 let mut nodes = create_network(3);
9646                 for node in nodes.iter() {
9647                         *node.keys_manager.override_session_priv.lock().unwrap() = Some(SecretKey::from_slice(&Secp256k1::without_caps(), &[3; 32]).unwrap());
9648                 }
9649                 let channels = [create_announced_chan_between_nodes(&nodes, 0, 1), create_announced_chan_between_nodes(&nodes, 1, 2)];
9650                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
9651                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap();
9652                 // positve case
9653                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000);
9654
9655                 // intermediate node failure
9656                 run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, |msg| {
9657                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9658                         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
9659                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9660                         let (mut onion_payloads, _htlc_msat, _htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height).unwrap();
9661                         onion_payloads[0].realm = 3;
9662                         msg.onion_routing_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
9663                 }, ||{}, 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
9664
9665                 // final node failure
9666                 run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, |msg| {
9667                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9668                         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
9669                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9670                         let (mut onion_payloads, _htlc_msat, _htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height).unwrap();
9671                         onion_payloads[1].realm = 3;
9672                         msg.onion_routing_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
9673                 }, ||{}, false, Some(PERM|1), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
9674
9675                 // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
9676                 // receiving simulated fail messages
9677                 // intermediate node failure
9678                 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
9679                         // trigger error
9680                         msg.amount_msat -= 1;
9681                 }, |msg| {
9682                         // and tamper returing error message
9683                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9684                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9685                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], NODE|2, &[0;0]);
9686                 }, ||{}, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: false}));
9687
9688                 // final node failure
9689                 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
9690                         // and tamper returing error message
9691                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9692                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9693                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], NODE|2, &[0;0]);
9694                 }, ||{
9695                         nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
9696                 }, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: false}));
9697
9698                 // intermediate node failure
9699                 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
9700                         msg.amount_msat -= 1;
9701                 }, |msg| {
9702                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9703                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9704                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|2, &[0;0]);
9705                 }, ||{}, true, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
9706
9707                 // final node failure
9708                 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
9709                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9710                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9711                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|2, &[0;0]);
9712                 }, ||{
9713                         nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
9714                 }, false, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
9715
9716                 // intermediate node failure
9717                 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
9718                         msg.amount_msat -= 1;
9719                 }, |msg| {
9720                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9721                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9722                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|3, &[0;0]);
9723                 }, ||{
9724                         nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
9725                 }, true, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
9726
9727                 // final node failure
9728                 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
9729                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9730                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9731                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|3, &[0;0]);
9732                 }, ||{
9733                         nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
9734                 }, false, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
9735
9736                 run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
9737                         Some(BADONION|PERM|4), None);
9738
9739                 run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
9740                         Some(BADONION|PERM|5), None);
9741
9742                 run_onion_failure_test("invalid_onion_key", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.public_key = Err(secp256k1::Error::InvalidPublicKey);}, ||{}, true,
9743                         Some(BADONION|PERM|6), None);
9744
9745                 run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
9746                         msg.amount_msat -= 1;
9747                 }, |msg| {
9748                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9749                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9750                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], UPDATE|7, &ChannelUpdate::dummy().encode_with_len()[..]);
9751                 }, ||{}, true, Some(UPDATE|7), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
9752
9753                 run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
9754                         msg.amount_msat -= 1;
9755                 }, |msg| {
9756                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9757                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9758                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|8, &[0;0]);
9759                         // short_channel_id from the processing node
9760                 }, ||{}, true, Some(PERM|8), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
9761
9762                 run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
9763                         msg.amount_msat -= 1;
9764                 }, |msg| {
9765                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9766                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9767                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|9, &[0;0]);
9768                         // short_channel_id from the processing node
9769                 }, ||{}, true, Some(PERM|9), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
9770
9771                 let mut bogus_route = route.clone();
9772                 bogus_route.hops[1].short_channel_id -= 1;
9773                 run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(PERM|10),
9774                   Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: bogus_route.hops[1].short_channel_id, is_permanent:true}));
9775
9776                 let amt_to_forward = nodes[1].node.channel_state.lock().unwrap().by_id.get(&channels[1].2).unwrap().get_their_htlc_minimum_msat() - 1;
9777                 let mut bogus_route = route.clone();
9778                 let route_len = bogus_route.hops.len();
9779                 bogus_route.hops[route_len-1].fee_msat = amt_to_forward;
9780                 run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(UPDATE|11), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
9781
9782                 //TODO: with new config API, we will be able to generate both valid and
9783                 //invalid channel_update cases.
9784                 run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, |msg| {
9785                         msg.amount_msat -= 1;
9786                 }, || {}, true, Some(UPDATE|12), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
9787
9788                 run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, |msg| {
9789                         // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
9790                         msg.cltv_expiry -= 1;
9791                 }, || {}, true, Some(UPDATE|13), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
9792
9793                 run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, |msg| {
9794                         let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - HTLC_FAIL_TIMEOUT_BLOCKS + 1;
9795                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9796                         nodes[1].chain_monitor.block_connected_checked(&header, height, &Vec::new()[..], &[0; 0]);
9797                 }, ||{}, true, Some(UPDATE|14), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
9798
9799                 run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, |_| {}, || {
9800                         nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
9801                 }, false, Some(PERM|15), None);
9802
9803                 run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, |msg| {
9804                         let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - HTLC_FAIL_TIMEOUT_BLOCKS + 1;
9805                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9806                         nodes[2].chain_monitor.block_connected_checked(&header, height, &Vec::new()[..], &[0; 0]);
9807                 }, || {}, true, Some(17), None);
9808
9809                 run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, |_| {}, || {
9810                         for (_, mut pending_forwards) in nodes[1].node.channel_state.lock().unwrap().borrow_parts().forward_htlcs.iter_mut() {
9811                                 for f in pending_forwards.iter_mut() {
9812                                         f.forward_info.outgoing_cltv_value += 1;
9813                                 }
9814                         }
9815                 }, true, Some(18), None);
9816
9817                 run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, |_| {}, || {
9818                         // violate amt_to_forward > msg.amount_msat
9819                         for (_, mut pending_forwards) in nodes[1].node.channel_state.lock().unwrap().borrow_parts().forward_htlcs.iter_mut() {
9820                                 for f in pending_forwards.iter_mut() {
9821                                         f.forward_info.amt_to_forward -= 1;
9822                                 }
9823                         }
9824                 }, true, Some(19), None);
9825
9826                 run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, |_| {}, || {
9827                         // disconnect event to the channel between nodes[1] ~ nodes[2]
9828                         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9829                         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9830                 }, true, Some(UPDATE|20), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
9831                 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9832
9833                 run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, |msg| {
9834                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9835                         let mut route = route.clone();
9836                         let height = 1;
9837                         route.hops[1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.hops[0].cltv_expiry_delta + 1;
9838                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9839                         let (onion_payloads, _, htlc_cltv) = ChannelManager::build_onion_payloads(&route, height).unwrap();
9840                         let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
9841                         msg.cltv_expiry = htlc_cltv;
9842                         msg.onion_routing_packet = onion_packet;
9843                 }, ||{}, true, Some(21), None);
9844         }
9845 }