Drop rust-crypto trait usage
[rust-lightning] / src / ln / channelmanager.rs
1 //! The top-level channel management and payment tracking stuff lives here.
2 //!
3 //! The ChannelManager is the main chunk of logic implementing the lightning protocol and is
4 //! responsible for tracking which channels are open, HTLCs are in flight and reestablishing those
5 //! upon reconnect to the relevant peer(s).
6 //!
7 //! It does not manage routing logic (see ln::router for that) nor does it manage constructing
8 //! on-chain transactions (it only monitors the chain to watch for any force-closes that might
9 //! imply it needs to fail HTLCs/payments/channels it manages).
10
11 use bitcoin::blockdata::block::BlockHeader;
12 use bitcoin::blockdata::transaction::Transaction;
13 use bitcoin::blockdata::constants::genesis_block;
14 use bitcoin::network::constants::Network;
15 use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
16
17 use bitcoin_hashes::{Hash, HashEngine};
18 use bitcoin_hashes::hmac::{Hmac, HmacEngine};
19 use bitcoin_hashes::sha256::Hash as Sha256;
20
21 use secp256k1::key::{SecretKey,PublicKey};
22 use secp256k1::{Secp256k1,Message};
23 use secp256k1::ecdh::SharedSecret;
24 use secp256k1;
25
26 use chain::chaininterface::{BroadcasterInterface,ChainListener,ChainWatchInterface,FeeEstimator};
27 use chain::transaction::OutPoint;
28 use ln::channel::{Channel, ChannelError};
29 use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, ManyChannelMonitor, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, HTLC_FAIL_ANTI_REORG_DELAY};
30 use ln::router::{Route,RouteHop};
31 use ln::msgs;
32 use ln::msgs::{ChannelMessageHandler, DecodeError, HandleError};
33 use chain::keysinterface::KeysInterface;
34 use util::config::UserConfig;
35 use util::{byte_utils, events, internal_traits, rng};
36 use util::ser::{Readable, ReadableArgs, Writeable, Writer};
37 use util::chacha20::ChaCha20;
38 use util::logger::Logger;
39 use util::errors::APIError;
40 use util::errors;
41
42 use crypto;
43
44 use std::{cmp, ptr, mem};
45 use std::collections::{HashMap, hash_map, HashSet};
46 use std::io::Cursor;
47 use std::sync::{Arc, Mutex, MutexGuard, RwLock};
48 use std::sync::atomic::{AtomicUsize, Ordering};
49 use std::time::{Instant,Duration};
50
51 /// We hold various information about HTLC relay in the HTLC objects in Channel itself:
52 ///
53 /// Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
54 /// forward the HTLC with information it will give back to us when it does so, or if it should Fail
55 /// the HTLC with the relevant message for the Channel to handle giving to the remote peer.
56 ///
57 /// When a Channel forwards an HTLC to its peer, it will give us back the PendingForwardHTLCInfo
58 /// which we will use to construct an outbound HTLC, with a relevant HTLCSource::PreviousHopData
59 /// filled in to indicate where it came from (which we can use to either fail-backwards or fulfill
60 /// the HTLC backwards along the relevant path).
61 /// Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
62 /// our payment, which we can use to decode errors or inform the user that the payment was sent.
63 mod channel_held_info {
64         use ln::msgs;
65         use ln::router::Route;
66         use ln::channelmanager::PaymentHash;
67         use secp256k1::key::SecretKey;
68
69         /// Stores the info we will need to send when we want to forward an HTLC onwards
70         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
71         pub struct PendingForwardHTLCInfo {
72                 pub(super) onion_packet: Option<msgs::OnionPacket>,
73                 pub(super) incoming_shared_secret: [u8; 32],
74                 pub(super) payment_hash: PaymentHash,
75                 pub(super) short_channel_id: u64,
76                 pub(super) amt_to_forward: u64,
77                 pub(super) outgoing_cltv_value: u32,
78         }
79
80         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
81         pub enum HTLCFailureMsg {
82                 Relay(msgs::UpdateFailHTLC),
83                 Malformed(msgs::UpdateFailMalformedHTLC),
84         }
85
86         /// Stores whether we can't forward an HTLC or relevant forwarding info
87         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
88         pub enum PendingHTLCStatus {
89                 Forward(PendingForwardHTLCInfo),
90                 Fail(HTLCFailureMsg),
91         }
92
93         /// Tracks the inbound corresponding to an outbound HTLC
94         #[derive(Clone, PartialEq)]
95         pub struct HTLCPreviousHopData {
96                 pub(super) short_channel_id: u64,
97                 pub(super) htlc_id: u64,
98                 pub(super) incoming_packet_shared_secret: [u8; 32],
99         }
100
101         /// Tracks the inbound corresponding to an outbound HTLC
102         #[derive(Clone, PartialEq)]
103         pub enum HTLCSource {
104                 PreviousHopData(HTLCPreviousHopData),
105                 OutboundRoute {
106                         route: Route,
107                         session_priv: SecretKey,
108                         /// Technically we can recalculate this from the route, but we cache it here to avoid
109                         /// doing a double-pass on route when we get a failure back
110                         first_hop_htlc_msat: u64,
111                 },
112         }
113         #[cfg(test)]
114         impl HTLCSource {
115                 pub fn dummy() -> Self {
116                         HTLCSource::OutboundRoute {
117                                 route: Route { hops: Vec::new() },
118                                 session_priv: SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[1; 32]).unwrap(),
119                                 first_hop_htlc_msat: 0,
120                         }
121                 }
122         }
123
124         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
125         pub(crate) enum HTLCFailReason {
126                 ErrorPacket {
127                         err: msgs::OnionErrorPacket,
128                 },
129                 Reason {
130                         failure_code: u16,
131                         data: Vec<u8>,
132                 }
133         }
134 }
135 pub(super) use self::channel_held_info::*;
136
137 /// payment_hash type, use to cross-lock hop
138 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
139 pub struct PaymentHash(pub [u8;32]);
140 /// payment_preimage type, use to route payment between hop
141 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
142 pub struct PaymentPreimage(pub [u8;32]);
143
144 type ShutdownResult = (Vec<Transaction>, Vec<(HTLCSource, PaymentHash)>);
145
146 /// Error type returned across the channel_state mutex boundary. When an Err is generated for a
147 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
148 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
149 /// channel_state lock. We then return the set of things that need to be done outside the lock in
150 /// this struct and call handle_error!() on it.
151
152 struct MsgHandleErrInternal {
153         err: msgs::HandleError,
154         shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
155 }
156 impl MsgHandleErrInternal {
157         #[inline]
158         fn send_err_msg_no_close(err: &'static str, channel_id: [u8; 32]) -> Self {
159                 Self {
160                         err: HandleError {
161                                 err,
162                                 action: Some(msgs::ErrorAction::SendErrorMessage {
163                                         msg: msgs::ErrorMessage {
164                                                 channel_id,
165                                                 data: err.to_string()
166                                         },
167                                 }),
168                         },
169                         shutdown_finish: None,
170                 }
171         }
172         #[inline]
173         fn from_no_close(err: msgs::HandleError) -> Self {
174                 Self { err, shutdown_finish: None }
175         }
176         #[inline]
177         fn from_finish_shutdown(err: &'static str, channel_id: [u8; 32], shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
178                 Self {
179                         err: HandleError {
180                                 err,
181                                 action: Some(msgs::ErrorAction::SendErrorMessage {
182                                         msg: msgs::ErrorMessage {
183                                                 channel_id,
184                                                 data: err.to_string()
185                                         },
186                                 }),
187                         },
188                         shutdown_finish: Some((shutdown_res, channel_update)),
189                 }
190         }
191         #[inline]
192         fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
193                 Self {
194                         err: match err {
195                                 ChannelError::Ignore(msg) => HandleError {
196                                         err: msg,
197                                         action: Some(msgs::ErrorAction::IgnoreError),
198                                 },
199                                 ChannelError::Close(msg) => HandleError {
200                                         err: msg,
201                                         action: Some(msgs::ErrorAction::SendErrorMessage {
202                                                 msg: msgs::ErrorMessage {
203                                                         channel_id,
204                                                         data: msg.to_string()
205                                                 },
206                                         }),
207                                 },
208                         },
209                         shutdown_finish: None,
210                 }
211         }
212 }
213
214 /// We hold back HTLCs we intend to relay for a random interval in the range (this, 5*this). This
215 /// provides some limited amount of privacy. Ideally this would range from somewhere like 1 second
216 /// to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly. We could
217 /// probably increase this significantly.
218 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
219
220 struct HTLCForwardInfo {
221         prev_short_channel_id: u64,
222         prev_htlc_id: u64,
223         forward_info: PendingForwardHTLCInfo,
224 }
225
226 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
227 /// be sent in the order they appear in the return value, however sometimes the order needs to be
228 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
229 /// they were originally sent). In those cases, this enum is also returned.
230 #[derive(Clone, PartialEq)]
231 pub(super) enum RAACommitmentOrder {
232         /// Send the CommitmentUpdate messages first
233         CommitmentFirst,
234         /// Send the RevokeAndACK message first
235         RevokeAndACKFirst,
236 }
237
238 struct ChannelHolder {
239         by_id: HashMap<[u8; 32], Channel>,
240         short_to_id: HashMap<u64, [u8; 32]>,
241         next_forward: Instant,
242         /// short channel id -> forward infos. Key of 0 means payments received
243         /// Note that while this is held in the same mutex as the channels themselves, no consistency
244         /// guarantees are made about there existing a channel with the short id here, nor the short
245         /// ids in the PendingForwardHTLCInfo!
246         forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
247         /// Note that while this is held in the same mutex as the channels themselves, no consistency
248         /// guarantees are made about the channels given here actually existing anymore by the time you
249         /// go to read them!
250         claimable_htlcs: HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
251         /// Messages to send to peers - pushed to in the same lock that they are generated in (except
252         /// for broadcast messages, where ordering isn't as strict).
253         pending_msg_events: Vec<events::MessageSendEvent>,
254 }
255 struct MutChannelHolder<'a> {
256         by_id: &'a mut HashMap<[u8; 32], Channel>,
257         short_to_id: &'a mut HashMap<u64, [u8; 32]>,
258         next_forward: &'a mut Instant,
259         forward_htlcs: &'a mut HashMap<u64, Vec<HTLCForwardInfo>>,
260         claimable_htlcs: &'a mut HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
261         pending_msg_events: &'a mut Vec<events::MessageSendEvent>,
262 }
263 impl ChannelHolder {
264         fn borrow_parts(&mut self) -> MutChannelHolder {
265                 MutChannelHolder {
266                         by_id: &mut self.by_id,
267                         short_to_id: &mut self.short_to_id,
268                         next_forward: &mut self.next_forward,
269                         forward_htlcs: &mut self.forward_htlcs,
270                         claimable_htlcs: &mut self.claimable_htlcs,
271                         pending_msg_events: &mut self.pending_msg_events,
272                 }
273         }
274 }
275
276 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
277 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
278
279 /// Manager which keeps track of a number of channels and sends messages to the appropriate
280 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
281 ///
282 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
283 /// to individual Channels.
284 ///
285 /// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
286 /// all peers during write/read (though does not modify this instance, only the instance being
287 /// serialized). This will result in any channels which have not yet exchanged funding_created (ie
288 /// called funding_transaction_generated for outbound channels).
289 ///
290 /// Note that you can be a bit lazier about writing out ChannelManager than you can be with
291 /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
292 /// returning from ManyChannelMonitor::add_update_monitor, with ChannelManagers, writing updates
293 /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during
294 /// the serialization process). If the deserialized version is out-of-date compared to the
295 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
296 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
297 ///
298 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelManager), which
299 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
300 /// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
301 /// block_connected() to step towards your best block) upon deserialization before using the
302 /// object!
303 pub struct ChannelManager {
304         default_configuration: UserConfig,
305         genesis_hash: Sha256dHash,
306         fee_estimator: Arc<FeeEstimator>,
307         monitor: Arc<ManyChannelMonitor>,
308         chain_monitor: Arc<ChainWatchInterface>,
309         tx_broadcaster: Arc<BroadcasterInterface>,
310
311         latest_block_height: AtomicUsize,
312         last_block_hash: Mutex<Sha256dHash>,
313         secp_ctx: Secp256k1<secp256k1::All>,
314
315         channel_state: Mutex<ChannelHolder>,
316         our_network_key: SecretKey,
317
318         pending_events: Mutex<Vec<events::Event>>,
319         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
320         /// Essentially just when we're serializing ourselves out.
321         /// Taken first everywhere where we are making changes before any other locks.
322         total_consistency_lock: RwLock<()>,
323
324         keys_manager: Arc<KeysInterface>,
325
326         logger: Arc<Logger>,
327 }
328
329 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
330 /// HTLC's CLTV. This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
331 /// ie the node we forwarded the payment on to should always have enough room to reliably time out
332 /// the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
333 /// CLTV_CLAIM_BUFFER point (we static assert that its at least 3 blocks more).
334 const CLTV_EXPIRY_DELTA: u16 = 6 * 12; //TODO?
335 const CLTV_FAR_FAR_AWAY: u32 = 6 * 24 * 7; //TODO?
336
337 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + 2*HTLC_FAIL_TIMEOUT_BLOCKS +
338 // HTLC_FAIL_ANTI_REORG_DELAY, ie that if the next-hop peer fails the HTLC within
339 // HTLC_FAIL_TIMEOUT_BLOCKS then we'll still have HTLC_FAIL_TIMEOUT_BLOCKS left to fail it
340 // backwards ourselves before hitting the CLTV_CLAIM_BUFFER point and failing the channel
341 // on-chain to time out the HTLC.
342 #[deny(const_err)]
343 #[allow(dead_code)]
344 const CHECK_CLTV_EXPIRY_SANITY: u32 = CLTV_EXPIRY_DELTA as u32 - 2*HTLC_FAIL_TIMEOUT_BLOCKS - CLTV_CLAIM_BUFFER - HTLC_FAIL_ANTI_REORG_DELAY;
345
346 // Check for ability of an attacker to make us fail on-chain by delaying inbound claim. See
347 // ChannelMontior::would_broadcast_at_height for a description of why this is needed.
348 #[deny(const_err)]
349 #[allow(dead_code)]
350 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = CLTV_EXPIRY_DELTA as u32 - HTLC_FAIL_TIMEOUT_BLOCKS - 2*CLTV_CLAIM_BUFFER;
351
352 macro_rules! secp_call {
353         ( $res: expr, $err: expr ) => {
354                 match $res {
355                         Ok(key) => key,
356                         Err(_) => return Err($err),
357                 }
358         };
359 }
360
361 struct OnionKeys {
362         #[cfg(test)]
363         shared_secret: SharedSecret,
364         #[cfg(test)]
365         blinding_factor: [u8; 32],
366         ephemeral_pubkey: PublicKey,
367         rho: [u8; 32],
368         mu: [u8; 32],
369 }
370
371 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
372 pub struct ChannelDetails {
373         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
374         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
375         /// Note that this means this value is *not* persistent - it can change once during the
376         /// lifetime of the channel.
377         pub channel_id: [u8; 32],
378         /// The position of the funding transaction in the chain. None if the funding transaction has
379         /// not yet been confirmed and the channel fully opened.
380         pub short_channel_id: Option<u64>,
381         /// The node_id of our counterparty
382         pub remote_network_id: PublicKey,
383         /// The value, in satoshis, of this channel as appears in the funding output
384         pub channel_value_satoshis: u64,
385         /// The user_id passed in to create_channel, or 0 if the channel was inbound.
386         pub user_id: u64,
387 }
388
389 macro_rules! handle_error {
390         ($self: ident, $internal: expr, $their_node_id: expr) => {
391                 match $internal {
392                         Ok(msg) => Ok(msg),
393                         Err(MsgHandleErrInternal { err, shutdown_finish }) => {
394                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
395                                         $self.finish_force_close_channel(shutdown_res);
396                                         if let Some(update) = update_option {
397                                                 let mut channel_state = $self.channel_state.lock().unwrap();
398                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
399                                                         msg: update
400                                                 });
401                                         }
402                                 }
403                                 Err(err)
404                         },
405                 }
406         }
407 }
408
409 macro_rules! break_chan_entry {
410         ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
411                 match $res {
412                         Ok(res) => res,
413                         Err(ChannelError::Ignore(msg)) => {
414                                 break Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
415                         },
416                         Err(ChannelError::Close(msg)) => {
417                                 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
418                                 let (channel_id, mut chan) = $entry.remove_entry();
419                                 if let Some(short_id) = chan.get_short_channel_id() {
420                                         $channel_state.short_to_id.remove(&short_id);
421                                 }
422                                 break Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
423                         },
424                 }
425         }
426 }
427
428 macro_rules! try_chan_entry {
429         ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
430                 match $res {
431                         Ok(res) => res,
432                         Err(ChannelError::Ignore(msg)) => {
433                                 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
434                         },
435                         Err(ChannelError::Close(msg)) => {
436                                 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
437                                 let (channel_id, mut chan) = $entry.remove_entry();
438                                 if let Some(short_id) = chan.get_short_channel_id() {
439                                         $channel_state.short_to_id.remove(&short_id);
440                                 }
441                                 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
442                         },
443                 }
444         }
445 }
446
447 macro_rules! return_monitor_err {
448         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
449                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new())
450         };
451         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $raa_first_dropped_cs: expr) => {
452                 if $action_type != RAACommitmentOrder::RevokeAndACKFirst { panic!("Bad return_monitor_err call!"); }
453                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new(), $raa_first_dropped_cs)
454         };
455         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr) => {
456                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, $failed_forwards, $failed_fails, false)
457         };
458         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr, $raa_first_dropped_cs: expr) => {
459                 match $err {
460                         ChannelMonitorUpdateErr::PermanentFailure => {
461                                 let (channel_id, mut chan) = $entry.remove_entry();
462                                 if let Some(short_id) = chan.get_short_channel_id() {
463                                         $channel_state.short_to_id.remove(&short_id);
464                                 }
465                                 // TODO: $failed_fails is dropped here, which will cause other channels to hit the
466                                 // chain in a confused state! We need to move them into the ChannelMonitor which
467                                 // will be responsible for failing backwards once things confirm on-chain.
468                                 // It's ok that we drop $failed_forwards here - at this point we'd rather they
469                                 // broadcast HTLC-Timeout and pay the associated fees to get their funds back than
470                                 // us bother trying to claim it just to forward on to another peer. If we're
471                                 // splitting hairs we'd prefer to claim payments that were to us, but we haven't
472                                 // given up the preimage yet, so might as well just wait until the payment is
473                                 // retried, avoiding the on-chain fees.
474                                 return Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
475                         },
476                         ChannelMonitorUpdateErr::TemporaryFailure => {
477                                 $entry.get_mut().monitor_update_failed($action_type, $failed_forwards, $failed_fails, $raa_first_dropped_cs);
478                                 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore("Failed to update ChannelMonitor"), *$entry.key()));
479                         },
480                 }
481         }
482 }
483
484 // Does not break in case of TemporaryFailure!
485 macro_rules! maybe_break_monitor_err {
486         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
487                 match $err {
488                         ChannelMonitorUpdateErr::PermanentFailure => {
489                                 let (channel_id, mut chan) = $entry.remove_entry();
490                                 if let Some(short_id) = chan.get_short_channel_id() {
491                                         $channel_state.short_to_id.remove(&short_id);
492                                 }
493                                 break Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
494                         },
495                         ChannelMonitorUpdateErr::TemporaryFailure => {
496                                 $entry.get_mut().monitor_update_failed($action_type, Vec::new(), Vec::new(), false);
497                         },
498                 }
499         }
500 }
501
502 impl ChannelManager {
503         /// Constructs a new ChannelManager to hold several channels and route between them.
504         ///
505         /// This is the main "logic hub" for all channel-related actions, and implements
506         /// ChannelMessageHandler.
507         ///
508         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
509         ///
510         /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
511         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> {
512                 let secp_ctx = Secp256k1::new();
513
514                 let res = Arc::new(ChannelManager {
515                         default_configuration: config.clone(),
516                         genesis_hash: genesis_block(network).header.bitcoin_hash(),
517                         fee_estimator: feeest.clone(),
518                         monitor: monitor.clone(),
519                         chain_monitor,
520                         tx_broadcaster,
521
522                         latest_block_height: AtomicUsize::new(0), //TODO: Get an init value
523                         last_block_hash: Mutex::new(Default::default()),
524                         secp_ctx,
525
526                         channel_state: Mutex::new(ChannelHolder{
527                                 by_id: HashMap::new(),
528                                 short_to_id: HashMap::new(),
529                                 next_forward: Instant::now(),
530                                 forward_htlcs: HashMap::new(),
531                                 claimable_htlcs: HashMap::new(),
532                                 pending_msg_events: Vec::new(),
533                         }),
534                         our_network_key: keys_manager.get_node_secret(),
535
536                         pending_events: Mutex::new(Vec::new()),
537                         total_consistency_lock: RwLock::new(()),
538
539                         keys_manager,
540
541                         logger,
542                 });
543                 let weak_res = Arc::downgrade(&res);
544                 res.chain_monitor.register_listener(weak_res);
545                 Ok(res)
546         }
547
548         /// Creates a new outbound channel to the given remote node and with the given value.
549         ///
550         /// user_id will be provided back as user_channel_id in FundingGenerationReady and
551         /// FundingBroadcastSafe events to allow tracking of which events correspond with which
552         /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
553         /// may wish to avoid using 0 for user_id here.
554         ///
555         /// If successful, will generate a SendOpenChannel message event, so you should probably poll
556         /// PeerManager::process_events afterwards.
557         ///
558         /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
559         /// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
560         pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64) -> Result<(), APIError> {
561                 if channel_value_satoshis < 1000 {
562                         return Err(APIError::APIMisuseError { err: "channel_value must be at least 1000 satoshis" });
563                 }
564
565                 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)?;
566                 let res = channel.get_open_channel(self.genesis_hash.clone(), &*self.fee_estimator);
567
568                 let _ = self.total_consistency_lock.read().unwrap();
569                 let mut channel_state = self.channel_state.lock().unwrap();
570                 match channel_state.by_id.entry(channel.channel_id()) {
571                         hash_map::Entry::Occupied(_) => {
572                                 if cfg!(feature = "fuzztarget") {
573                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG" });
574                                 } else {
575                                         panic!("RNG is bad???");
576                                 }
577                         },
578                         hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
579                 }
580                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
581                         node_id: their_network_key,
582                         msg: res,
583                 });
584                 Ok(())
585         }
586
587         /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
588         /// more information.
589         pub fn list_channels(&self) -> Vec<ChannelDetails> {
590                 let channel_state = self.channel_state.lock().unwrap();
591                 let mut res = Vec::with_capacity(channel_state.by_id.len());
592                 for (channel_id, channel) in channel_state.by_id.iter() {
593                         res.push(ChannelDetails {
594                                 channel_id: (*channel_id).clone(),
595                                 short_channel_id: channel.get_short_channel_id(),
596                                 remote_network_id: channel.get_their_node_id(),
597                                 channel_value_satoshis: channel.get_value_satoshis(),
598                                 user_id: channel.get_user_id(),
599                         });
600                 }
601                 res
602         }
603
604         /// Gets the list of usable channels, in random order. Useful as an argument to
605         /// Router::get_route to ensure non-announced channels are used.
606         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
607                 let channel_state = self.channel_state.lock().unwrap();
608                 let mut res = Vec::with_capacity(channel_state.by_id.len());
609                 for (channel_id, channel) in channel_state.by_id.iter() {
610                         // Note we use is_live here instead of usable which leads to somewhat confused
611                         // internal/external nomenclature, but that's ok cause that's probably what the user
612                         // really wanted anyway.
613                         if channel.is_live() {
614                                 res.push(ChannelDetails {
615                                         channel_id: (*channel_id).clone(),
616                                         short_channel_id: channel.get_short_channel_id(),
617                                         remote_network_id: channel.get_their_node_id(),
618                                         channel_value_satoshis: channel.get_value_satoshis(),
619                                         user_id: channel.get_user_id(),
620                                 });
621                         }
622                 }
623                 res
624         }
625
626         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
627         /// will be accepted on the given channel, and after additional timeout/the closing of all
628         /// pending HTLCs, the channel will be closed on chain.
629         ///
630         /// May generate a SendShutdown message event on success, which should be relayed.
631         pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
632                 let _ = self.total_consistency_lock.read().unwrap();
633
634                 let (mut failed_htlcs, chan_option) = {
635                         let mut channel_state_lock = self.channel_state.lock().unwrap();
636                         let channel_state = channel_state_lock.borrow_parts();
637                         match channel_state.by_id.entry(channel_id.clone()) {
638                                 hash_map::Entry::Occupied(mut chan_entry) => {
639                                         let (shutdown_msg, failed_htlcs) = chan_entry.get_mut().get_shutdown()?;
640                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
641                                                 node_id: chan_entry.get().get_their_node_id(),
642                                                 msg: shutdown_msg
643                                         });
644                                         if chan_entry.get().is_shutdown() {
645                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
646                                                         channel_state.short_to_id.remove(&short_id);
647                                                 }
648                                                 (failed_htlcs, Some(chan_entry.remove_entry().1))
649                                         } else { (failed_htlcs, None) }
650                                 },
651                                 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: "No such channel"})
652                         }
653                 };
654                 for htlc_source in failed_htlcs.drain(..) {
655                         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() });
656                 }
657                 let chan_update = if let Some(chan) = chan_option {
658                         if let Ok(update) = self.get_channel_update(&chan) {
659                                 Some(update)
660                         } else { None }
661                 } else { None };
662
663                 if let Some(update) = chan_update {
664                         let mut channel_state = self.channel_state.lock().unwrap();
665                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
666                                 msg: update
667                         });
668                 }
669
670                 Ok(())
671         }
672
673         #[inline]
674         fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
675                 let (local_txn, mut failed_htlcs) = shutdown_res;
676                 log_trace!(self, "Finishing force-closure of channel with {} transactions to broadcast and {} HTLCs to fail", local_txn.len(), failed_htlcs.len());
677                 for htlc_source in failed_htlcs.drain(..) {
678                         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() });
679                 }
680                 for tx in local_txn {
681                         self.tx_broadcaster.broadcast_transaction(&tx);
682                 }
683         }
684
685         /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
686         /// the chain and rejecting new HTLCs on the given channel.
687         pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
688                 let _ = self.total_consistency_lock.read().unwrap();
689
690                 let mut chan = {
691                         let mut channel_state_lock = self.channel_state.lock().unwrap();
692                         let channel_state = channel_state_lock.borrow_parts();
693                         if let Some(chan) = channel_state.by_id.remove(channel_id) {
694                                 if let Some(short_id) = chan.get_short_channel_id() {
695                                         channel_state.short_to_id.remove(&short_id);
696                                 }
697                                 chan
698                         } else {
699                                 return;
700                         }
701                 };
702                 log_trace!(self, "Force-closing channel {}", log_bytes!(channel_id[..]));
703                 self.finish_force_close_channel(chan.force_shutdown());
704                 if let Ok(update) = self.get_channel_update(&chan) {
705                         let mut channel_state = self.channel_state.lock().unwrap();
706                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
707                                 msg: update
708                         });
709                 }
710         }
711
712         /// Force close all channels, immediately broadcasting the latest local commitment transaction
713         /// for each to the chain and rejecting new HTLCs on each.
714         pub fn force_close_all_channels(&self) {
715                 for chan in self.list_channels() {
716                         self.force_close_channel(&chan.channel_id);
717                 }
718         }
719
720         #[inline]
721         fn gen_rho_mu_from_shared_secret(shared_secret: &[u8]) -> ([u8; 32], [u8; 32]) {
722                 assert_eq!(shared_secret.len(), 32);
723                 ({
724                         let mut hmac = HmacEngine::<Sha256>::new(&[0x72, 0x68, 0x6f]); // rho
725                         hmac.input(&shared_secret[..]);
726                         Hmac::from_engine(hmac).into_inner()
727                 },
728                 {
729                         let mut hmac = HmacEngine::<Sha256>::new(&[0x6d, 0x75]); // mu
730                         hmac.input(&shared_secret[..]);
731                         Hmac::from_engine(hmac).into_inner()
732                 })
733         }
734
735         #[inline]
736         fn gen_um_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
737                 assert_eq!(shared_secret.len(), 32);
738                 let mut hmac = HmacEngine::<Sha256>::new(&[0x75, 0x6d]); // um
739                 hmac.input(&shared_secret[..]);
740                 Hmac::from_engine(hmac).into_inner()
741         }
742
743         #[inline]
744         fn gen_ammag_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
745                 assert_eq!(shared_secret.len(), 32);
746                 let mut hmac = HmacEngine::<Sha256>::new(&[0x61, 0x6d, 0x6d, 0x61, 0x67]); // ammag
747                 hmac.input(&shared_secret[..]);
748                 Hmac::from_engine(hmac).into_inner()
749         }
750
751         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
752         #[inline]
753         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> {
754                 let mut blinded_priv = session_priv.clone();
755                 let mut blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
756
757                 for hop in route.hops.iter() {
758                         let shared_secret = SharedSecret::new(secp_ctx, &hop.pubkey, &blinded_priv);
759
760                         let mut sha = Sha256::engine();
761                         sha.input(&blinded_pub.serialize()[..]);
762                         sha.input(&shared_secret[..]);
763                         let blinding_factor = Sha256::from_engine(sha).into_inner();
764
765                         let ephemeral_pubkey = blinded_pub;
766
767                         blinded_priv.mul_assign(secp_ctx, &SecretKey::from_slice(secp_ctx, &blinding_factor)?)?;
768                         blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
769
770                         callback(shared_secret, blinding_factor, ephemeral_pubkey, hop);
771                 }
772
773                 Ok(())
774         }
775
776         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
777         fn construct_onion_keys<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey) -> Result<Vec<OnionKeys>, secp256k1::Error> {
778                 let mut res = Vec::with_capacity(route.hops.len());
779
780                 Self::construct_onion_keys_callback(secp_ctx, route, session_priv, |shared_secret, _blinding_factor, ephemeral_pubkey, _| {
781                         let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret[..]);
782
783                         res.push(OnionKeys {
784                                 #[cfg(test)]
785                                 shared_secret,
786                                 #[cfg(test)]
787                                 blinding_factor: _blinding_factor,
788                                 ephemeral_pubkey,
789                                 rho,
790                                 mu,
791                         });
792                 })?;
793
794                 Ok(res)
795         }
796
797         /// returns the hop data, as well as the first-hop value_msat and CLTV value we should send.
798         fn build_onion_payloads(route: &Route, starting_htlc_offset: u32) -> Result<(Vec<msgs::OnionHopData>, u64, u32), APIError> {
799                 let mut cur_value_msat = 0u64;
800                 let mut cur_cltv = starting_htlc_offset;
801                 let mut last_short_channel_id = 0;
802                 let mut res: Vec<msgs::OnionHopData> = Vec::with_capacity(route.hops.len());
803                 internal_traits::test_no_dealloc::<msgs::OnionHopData>(None);
804                 unsafe { res.set_len(route.hops.len()); }
805
806                 for (idx, hop) in route.hops.iter().enumerate().rev() {
807                         // First hop gets special values so that it can check, on receipt, that everything is
808                         // exactly as it should be (and the next hop isn't trying to probe to find out if we're
809                         // the intended recipient).
810                         let value_msat = if cur_value_msat == 0 { hop.fee_msat } else { cur_value_msat };
811                         let cltv = if cur_cltv == starting_htlc_offset { hop.cltv_expiry_delta + starting_htlc_offset } else { cur_cltv };
812                         res[idx] = msgs::OnionHopData {
813                                 realm: 0,
814                                 data: msgs::OnionRealm0HopData {
815                                         short_channel_id: last_short_channel_id,
816                                         amt_to_forward: value_msat,
817                                         outgoing_cltv_value: cltv,
818                                 },
819                                 hmac: [0; 32],
820                         };
821                         cur_value_msat += hop.fee_msat;
822                         if cur_value_msat >= 21000000 * 100000000 * 1000 {
823                                 return Err(APIError::RouteError{err: "Channel fees overflowed?!"});
824                         }
825                         cur_cltv += hop.cltv_expiry_delta as u32;
826                         if cur_cltv >= 500000000 {
827                                 return Err(APIError::RouteError{err: "Channel CLTV overflowed?!"});
828                         }
829                         last_short_channel_id = hop.short_channel_id;
830                 }
831                 Ok((res, cur_value_msat, cur_cltv))
832         }
833
834         #[inline]
835         fn shift_arr_right(arr: &mut [u8; 20*65]) {
836                 unsafe {
837                         ptr::copy(arr[0..].as_ptr(), arr[65..].as_mut_ptr(), 19*65);
838                 }
839                 for i in 0..65 {
840                         arr[i] = 0;
841                 }
842         }
843
844         #[inline]
845         fn xor_bufs(dst: &mut[u8], src: &[u8]) {
846                 assert_eq!(dst.len(), src.len());
847
848                 for i in 0..dst.len() {
849                         dst[i] ^= src[i];
850                 }
851         }
852
853         const ZERO:[u8; 21*65] = [0; 21*65];
854         fn construct_onion_packet(mut payloads: Vec<msgs::OnionHopData>, onion_keys: Vec<OnionKeys>, associated_data: &PaymentHash) -> msgs::OnionPacket {
855                 let mut buf = Vec::with_capacity(21*65);
856                 buf.resize(21*65, 0);
857
858                 let filler = {
859                         let iters = payloads.len() - 1;
860                         let end_len = iters * 65;
861                         let mut res = Vec::with_capacity(end_len);
862                         res.resize(end_len, 0);
863
864                         for (i, keys) in onion_keys.iter().enumerate() {
865                                 if i == payloads.len() - 1 { continue; }
866                                 let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
867                                 chacha.process(&ChannelManager::ZERO, &mut buf); // We don't have a seek function :(
868                                 ChannelManager::xor_bufs(&mut res[0..(i + 1)*65], &buf[(20 - i)*65..21*65]);
869                         }
870                         res
871                 };
872
873                 let mut packet_data = [0; 20*65];
874                 let mut hmac_res = [0; 32];
875
876                 for (i, (payload, keys)) in payloads.iter_mut().zip(onion_keys.iter()).rev().enumerate() {
877                         ChannelManager::shift_arr_right(&mut packet_data);
878                         payload.hmac = hmac_res;
879                         packet_data[0..65].copy_from_slice(&payload.encode()[..]);
880
881                         let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
882                         chacha.process(&packet_data, &mut buf[0..20*65]);
883                         packet_data[..].copy_from_slice(&buf[0..20*65]);
884
885                         if i == 0 {
886                                 packet_data[20*65 - filler.len()..20*65].copy_from_slice(&filler[..]);
887                         }
888
889                         let mut hmac = HmacEngine::<Sha256>::new(&keys.mu);
890                         hmac.input(&packet_data);
891                         hmac.input(&associated_data.0[..]);
892                         hmac_res = Hmac::from_engine(hmac).into_inner();
893                 }
894
895                 msgs::OnionPacket{
896                         version: 0,
897                         public_key: Ok(onion_keys.first().unwrap().ephemeral_pubkey),
898                         hop_data: packet_data,
899                         hmac: hmac_res,
900                 }
901         }
902
903         /// Encrypts a failure packet. raw_packet can either be a
904         /// msgs::DecodedOnionErrorPacket.encode() result or a msgs::OnionErrorPacket.data element.
905         fn encrypt_failure_packet(shared_secret: &[u8], raw_packet: &[u8]) -> msgs::OnionErrorPacket {
906                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
907
908                 let mut packet_crypted = Vec::with_capacity(raw_packet.len());
909                 packet_crypted.resize(raw_packet.len(), 0);
910                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
911                 chacha.process(&raw_packet, &mut packet_crypted[..]);
912                 msgs::OnionErrorPacket {
913                         data: packet_crypted,
914                 }
915         }
916
917         fn build_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::DecodedOnionErrorPacket {
918                 assert_eq!(shared_secret.len(), 32);
919                 assert!(failure_data.len() <= 256 - 2);
920
921                 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
922
923                 let failuremsg = {
924                         let mut res = Vec::with_capacity(2 + failure_data.len());
925                         res.push(((failure_type >> 8) & 0xff) as u8);
926                         res.push(((failure_type >> 0) & 0xff) as u8);
927                         res.extend_from_slice(&failure_data[..]);
928                         res
929                 };
930                 let pad = {
931                         let mut res = Vec::with_capacity(256 - 2 - failure_data.len());
932                         res.resize(256 - 2 - failure_data.len(), 0);
933                         res
934                 };
935                 let mut packet = msgs::DecodedOnionErrorPacket {
936                         hmac: [0; 32],
937                         failuremsg: failuremsg,
938                         pad: pad,
939                 };
940
941                 let mut hmac = HmacEngine::<Sha256>::new(&um);
942                 hmac.input(&packet.encode()[32..]);
943                 packet.hmac = Hmac::from_engine(hmac).into_inner();
944
945                 packet
946         }
947
948         #[inline]
949         fn build_first_hop_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::OnionErrorPacket {
950                 let failure_packet = ChannelManager::build_failure_packet(shared_secret, failure_type, failure_data);
951                 ChannelManager::encrypt_failure_packet(shared_secret, &failure_packet.encode()[..])
952         }
953
954         fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder>) {
955                 macro_rules! return_malformed_err {
956                         ($msg: expr, $err_code: expr) => {
957                                 {
958                                         log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
959                                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
960                                                 channel_id: msg.channel_id,
961                                                 htlc_id: msg.htlc_id,
962                                                 sha256_of_onion: Sha256::hash(&msg.onion_routing_packet.hop_data).into_inner(),
963                                                 failure_code: $err_code,
964                                         })), self.channel_state.lock().unwrap());
965                                 }
966                         }
967                 }
968
969                 if let Err(_) = msg.onion_routing_packet.public_key {
970                         return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
971                 }
972
973                 let shared_secret = {
974                         let mut arr = [0; 32];
975                         arr.copy_from_slice(&SharedSecret::new(&self.secp_ctx, &msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key)[..]);
976                         arr
977                 };
978                 let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
979
980                 if msg.onion_routing_packet.version != 0 {
981                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
982                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
983                         //the hash doesn't really serve any purpuse - in the case of hashing all data, the
984                         //receiving node would have to brute force to figure out which version was put in the
985                         //packet by the node that send us the message, in the case of hashing the hop_data, the
986                         //node knows the HMAC matched, so they already know what is there...
987                         return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
988                 }
989
990
991                 let mut hmac = HmacEngine::<Sha256>::new(&mu);
992                 hmac.input(&msg.onion_routing_packet.hop_data);
993                 hmac.input(&msg.payment_hash.0[..]);
994                 if !crypto::util::fixed_time_eq(&Hmac::from_engine(hmac).into_inner(), &msg.onion_routing_packet.hmac) {
995                         return_malformed_err!("HMAC Check failed", 0x8000 | 0x4000 | 5);
996                 }
997
998                 let mut channel_state = None;
999                 macro_rules! return_err {
1000                         ($msg: expr, $err_code: expr, $data: expr) => {
1001                                 {
1002                                         log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
1003                                         if channel_state.is_none() {
1004                                                 channel_state = Some(self.channel_state.lock().unwrap());
1005                                         }
1006                                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
1007                                                 channel_id: msg.channel_id,
1008                                                 htlc_id: msg.htlc_id,
1009                                                 reason: ChannelManager::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
1010                                         })), channel_state.unwrap());
1011                                 }
1012                         }
1013                 }
1014
1015                 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
1016                 let next_hop_data = {
1017                         let mut decoded = [0; 65];
1018                         chacha.process(&msg.onion_routing_packet.hop_data[0..65], &mut decoded);
1019                         match msgs::OnionHopData::read(&mut Cursor::new(&decoded[..])) {
1020                                 Err(err) => {
1021                                         let error_code = match err {
1022                                                 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
1023                                                 _ => 0x2000 | 2, // Should never happen
1024                                         };
1025                                         return_err!("Unable to decode our hop data", error_code, &[0;0]);
1026                                 },
1027                                 Ok(msg) => msg
1028                         }
1029                 };
1030
1031                 let pending_forward_info = if next_hop_data.hmac == [0; 32] {
1032                                 // OUR PAYMENT!
1033                                 // final_expiry_too_soon
1034                                 if (msg.cltv_expiry as u64) < self.latest_block_height.load(Ordering::Acquire) as u64 + (CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS) as u64 {
1035                                         return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
1036                                 }
1037                                 // final_incorrect_htlc_amount
1038                                 if next_hop_data.data.amt_to_forward > msg.amount_msat {
1039                                         return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
1040                                 }
1041                                 // final_incorrect_cltv_expiry
1042                                 if next_hop_data.data.outgoing_cltv_value != msg.cltv_expiry {
1043                                         return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
1044                                 }
1045
1046                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
1047                                 // message, however that would leak that we are the recipient of this payment, so
1048                                 // instead we stay symmetric with the forwarding case, only responding (after a
1049                                 // delay) once they've send us a commitment_signed!
1050
1051                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1052                                         onion_packet: None,
1053                                         payment_hash: msg.payment_hash.clone(),
1054                                         short_channel_id: 0,
1055                                         incoming_shared_secret: shared_secret,
1056                                         amt_to_forward: next_hop_data.data.amt_to_forward,
1057                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1058                                 })
1059                         } else {
1060                                 let mut new_packet_data = [0; 20*65];
1061                                 chacha.process(&msg.onion_routing_packet.hop_data[65..], &mut new_packet_data[0..19*65]);
1062                                 chacha.process(&ChannelManager::ZERO[0..65], &mut new_packet_data[19*65..]);
1063
1064                                 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
1065
1066                                 let blinding_factor = {
1067                                         let mut sha = Sha256::engine();
1068                                         sha.input(&new_pubkey.serialize()[..]);
1069                                         sha.input(&shared_secret);
1070                                         SecretKey::from_slice(&self.secp_ctx, &Sha256::from_engine(sha).into_inner()).expect("SHA-256 is broken?")
1071                                 };
1072
1073                                 let public_key = if let Err(e) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor) {
1074                                         Err(e)
1075                                 } else { Ok(new_pubkey) };
1076
1077                                 let outgoing_packet = msgs::OnionPacket {
1078                                         version: 0,
1079                                         public_key,
1080                                         hop_data: new_packet_data,
1081                                         hmac: next_hop_data.hmac.clone(),
1082                                 };
1083
1084                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1085                                         onion_packet: Some(outgoing_packet),
1086                                         payment_hash: msg.payment_hash.clone(),
1087                                         short_channel_id: next_hop_data.data.short_channel_id,
1088                                         incoming_shared_secret: shared_secret,
1089                                         amt_to_forward: next_hop_data.data.amt_to_forward,
1090                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1091                                 })
1092                         };
1093
1094                 channel_state = Some(self.channel_state.lock().unwrap());
1095                 if let &PendingHTLCStatus::Forward(PendingForwardHTLCInfo { ref onion_packet, ref short_channel_id, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
1096                         if onion_packet.is_some() { // If short_channel_id is 0 here, we'll reject them in the body here
1097                                 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
1098                                 let forwarding_id = match id_option {
1099                                         None => { // unknown_next_peer
1100                                                 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
1101                                         },
1102                                         Some(id) => id.clone(),
1103                                 };
1104                                 if let Some((err, code, chan_update)) = loop {
1105                                         let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
1106
1107                                         // Note that we could technically not return an error yet here and just hope
1108                                         // that the connection is reestablished or monitor updated by the time we get
1109                                         // around to doing the actual forward, but better to fail early if we can and
1110                                         // hopefully an attacker trying to path-trace payments cannot make this occur
1111                                         // on a small/per-node/per-channel scale.
1112                                         if !chan.is_live() { // channel_disabled
1113                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
1114                                         }
1115                                         if *amt_to_forward < chan.get_their_htlc_minimum_msat() { // amount_below_minimum
1116                                                 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
1117                                         }
1118                                         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) });
1119                                         if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
1120                                                 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())));
1121                                         }
1122                                         if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 { // incorrect_cltv_expiry
1123                                                 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())));
1124                                         }
1125                                         let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1126                                         // We want to have at least HTLC_FAIL_TIMEOUT_BLOCKS to fail prior to going on chain CLAIM_BUFFER blocks before expiration
1127                                         if msg.cltv_expiry <= cur_height + CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS as u32 { // expiry_too_soon
1128                                                 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1129                                         }
1130                                         if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
1131                                                 break Some(("CLTV expiry is too far in the future", 21, None));
1132                                         }
1133                                         break None;
1134                                 }
1135                                 {
1136                                         let mut res = Vec::with_capacity(8 + 128);
1137                                         if let Some(chan_update) = chan_update {
1138                                                 if code == 0x1000 | 11 || code == 0x1000 | 12 {
1139                                                         res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
1140                                                 }
1141                                                 else if code == 0x1000 | 13 {
1142                                                         res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
1143                                                 }
1144                                                 else if code == 0x1000 | 20 {
1145                                                         res.extend_from_slice(&byte_utils::be16_to_array(chan_update.contents.flags));
1146                                                 }
1147                                                 res.extend_from_slice(&chan_update.encode_with_len()[..]);
1148                                         }
1149                                         return_err!(err, code, &res[..]);
1150                                 }
1151                         }
1152                 }
1153
1154                 (pending_forward_info, channel_state.unwrap())
1155         }
1156
1157         /// only fails if the channel does not yet have an assigned short_id
1158         /// May be called with channel_state already locked!
1159         fn get_channel_update(&self, chan: &Channel) -> Result<msgs::ChannelUpdate, HandleError> {
1160                 let short_channel_id = match chan.get_short_channel_id() {
1161                         None => return Err(HandleError{err: "Channel not yet established", action: None}),
1162                         Some(id) => id,
1163                 };
1164
1165                 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_their_node_id().serialize()[..];
1166
1167                 let unsigned = msgs::UnsignedChannelUpdate {
1168                         chain_hash: self.genesis_hash,
1169                         short_channel_id: short_channel_id,
1170                         timestamp: chan.get_channel_update_count(),
1171                         flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
1172                         cltv_expiry_delta: CLTV_EXPIRY_DELTA,
1173                         htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
1174                         fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
1175                         fee_proportional_millionths: chan.get_fee_proportional_millionths(),
1176                         excess_data: Vec::new(),
1177                 };
1178
1179                 let msg_hash = Sha256dHash::from_data(&unsigned.encode()[..]);
1180                 let sig = self.secp_ctx.sign(&Message::from_slice(&msg_hash[..]).unwrap(), &self.our_network_key);
1181
1182                 Ok(msgs::ChannelUpdate {
1183                         signature: sig,
1184                         contents: unsigned
1185                 })
1186         }
1187
1188         /// Sends a payment along a given route.
1189         ///
1190         /// Value parameters are provided via the last hop in route, see documentation for RouteHop
1191         /// fields for more info.
1192         ///
1193         /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
1194         /// payment), we don't do anything to stop you! We always try to ensure that if the provided
1195         /// next hop knows the preimage to payment_hash they can claim an additional amount as
1196         /// specified in the last hop in the route! Thus, you should probably do your own
1197         /// payment_preimage tracking (which you should already be doing as they represent "proof of
1198         /// payment") and prevent double-sends yourself.
1199         ///
1200         /// May generate a SendHTLCs message event on success, which should be relayed.
1201         ///
1202         /// Raises APIError::RoutError when invalid route or forward parameter
1203         /// (cltv_delta, fee, node public key) is specified.
1204         /// Raises APIError::ChannelUnavailable if the next-hop channel is not available for updates
1205         /// (including due to previous monitor update failure or new permanent monitor update failure).
1206         /// Raised APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
1207         /// relevant updates.
1208         ///
1209         /// In case of APIError::RouteError/APIError::ChannelUnavailable, the payment send has failed
1210         /// and you may wish to retry via a different route immediately.
1211         /// In case of APIError::MonitorUpdateFailed, the commitment update has been irrevocably
1212         /// committed on our end and we're just waiting for a monitor update to send it. Do NOT retry
1213         /// the payment via a different route unless you intend to pay twice!
1214         pub fn send_payment(&self, route: Route, payment_hash: PaymentHash) -> Result<(), APIError> {
1215                 if route.hops.len() < 1 || route.hops.len() > 20 {
1216                         return Err(APIError::RouteError{err: "Route didn't go anywhere/had bogus size"});
1217                 }
1218                 let our_node_id = self.get_our_node_id();
1219                 for (idx, hop) in route.hops.iter().enumerate() {
1220                         if idx != route.hops.len() - 1 && hop.pubkey == our_node_id {
1221                                 return Err(APIError::RouteError{err: "Route went through us but wasn't a simple rebalance loop to us"});
1222                         }
1223                 }
1224
1225                 let session_priv = self.keys_manager.get_session_key();
1226
1227                 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1228
1229                 let onion_keys = secp_call!(ChannelManager::construct_onion_keys(&self.secp_ctx, &route, &session_priv),
1230                                 APIError::RouteError{err: "Pubkey along hop was maliciously selected"});
1231                 let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height)?;
1232                 let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
1233
1234                 let _ = self.total_consistency_lock.read().unwrap();
1235
1236                 let err: Result<(), _> = loop {
1237                         let mut channel_lock = self.channel_state.lock().unwrap();
1238
1239                         let id = match channel_lock.short_to_id.get(&route.hops.first().unwrap().short_channel_id) {
1240                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!"}),
1241                                 Some(id) => id.clone(),
1242                         };
1243
1244                         let channel_state = channel_lock.borrow_parts();
1245                         if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) {
1246                                 match {
1247                                         if chan.get().get_their_node_id() != route.hops.first().unwrap().pubkey {
1248                                                 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1249                                         }
1250                                         if !chan.get().is_live() {
1251                                                 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!"});
1252                                         }
1253                                         break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1254                                                 route: route.clone(),
1255                                                 session_priv: session_priv.clone(),
1256                                                 first_hop_htlc_msat: htlc_msat,
1257                                         }, onion_packet), channel_state, chan)
1258                                 } {
1259                                         Some((update_add, commitment_signed, chan_monitor)) => {
1260                                                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1261                                                         maybe_break_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst);
1262                                                         // Note that MonitorUpdateFailed here indicates (per function docs)
1263                                                         // that we will resent the commitment update once we unfree monitor
1264                                                         // updating, so we have to take special care that we don't return
1265                                                         // something else in case we will resend later!
1266                                                         return Err(APIError::MonitorUpdateFailed);
1267                                                 }
1268
1269                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1270                                                         node_id: route.hops.first().unwrap().pubkey,
1271                                                         updates: msgs::CommitmentUpdate {
1272                                                                 update_add_htlcs: vec![update_add],
1273                                                                 update_fulfill_htlcs: Vec::new(),
1274                                                                 update_fail_htlcs: Vec::new(),
1275                                                                 update_fail_malformed_htlcs: Vec::new(),
1276                                                                 update_fee: None,
1277                                                                 commitment_signed,
1278                                                         },
1279                                                 });
1280                                         },
1281                                         None => {},
1282                                 }
1283                         } else { unreachable!(); }
1284                         return Ok(());
1285                 };
1286
1287                 match handle_error!(self, err, route.hops.first().unwrap().pubkey) {
1288                         Ok(_) => unreachable!(),
1289                         Err(e) => {
1290                                 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
1291                                 } else {
1292                                         log_error!(self, "Got bad keys: {}!", e.err);
1293                                         let mut channel_state = self.channel_state.lock().unwrap();
1294                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1295                                                 node_id: route.hops.first().unwrap().pubkey,
1296                                                 action: e.action,
1297                                         });
1298                                 }
1299                                 Err(APIError::ChannelUnavailable { err: e.err })
1300                         },
1301                 }
1302         }
1303
1304         /// Call this upon creation of a funding transaction for the given channel.
1305         ///
1306         /// Note that ALL inputs in the transaction pointed to by funding_txo MUST spend SegWit outputs
1307         /// or your counterparty can steal your funds!
1308         ///
1309         /// Panics if a funding transaction has already been provided for this channel.
1310         ///
1311         /// May panic if the funding_txo is duplicative with some other channel (note that this should
1312         /// be trivially prevented by using unique funding transaction keys per-channel).
1313         pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1314                 let _ = self.total_consistency_lock.read().unwrap();
1315
1316                 let (chan, msg, chan_monitor) = {
1317                         let (res, chan) = {
1318                                 let mut channel_state = self.channel_state.lock().unwrap();
1319                                 match channel_state.by_id.remove(temporary_channel_id) {
1320                                         Some(mut chan) => {
1321                                                 (chan.get_outbound_funding_created(funding_txo)
1322                                                         .map_err(|e| if let ChannelError::Close(msg) = e {
1323                                                                 MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.force_shutdown(), None)
1324                                                         } else { unreachable!(); })
1325                                                 , chan)
1326                                         },
1327                                         None => return
1328                                 }
1329                         };
1330                         match handle_error!(self, res, chan.get_their_node_id()) {
1331                                 Ok(funding_msg) => {
1332                                         (chan, funding_msg.0, funding_msg.1)
1333                                 },
1334                                 Err(e) => {
1335                                         log_error!(self, "Got bad signatures: {}!", e.err);
1336                                         let mut channel_state = self.channel_state.lock().unwrap();
1337                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1338                                                 node_id: chan.get_their_node_id(),
1339                                                 action: e.action,
1340                                         });
1341                                         return;
1342                                 },
1343                         }
1344                 };
1345                 // Because we have exclusive ownership of the channel here we can release the channel_state
1346                 // lock before add_update_monitor
1347                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1348                         unimplemented!();
1349                 }
1350
1351                 let mut channel_state = self.channel_state.lock().unwrap();
1352                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
1353                         node_id: chan.get_their_node_id(),
1354                         msg: msg,
1355                 });
1356                 match channel_state.by_id.entry(chan.channel_id()) {
1357                         hash_map::Entry::Occupied(_) => {
1358                                 panic!("Generated duplicate funding txid?");
1359                         },
1360                         hash_map::Entry::Vacant(e) => {
1361                                 e.insert(chan);
1362                         }
1363                 }
1364         }
1365
1366         fn get_announcement_sigs(&self, chan: &Channel) -> Option<msgs::AnnouncementSignatures> {
1367                 if !chan.should_announce() { return None }
1368
1369                 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1370                         Ok(res) => res,
1371                         Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1372                 };
1373                 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
1374                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1375
1376                 Some(msgs::AnnouncementSignatures {
1377                         channel_id: chan.channel_id(),
1378                         short_channel_id: chan.get_short_channel_id().unwrap(),
1379                         node_signature: our_node_sig,
1380                         bitcoin_signature: our_bitcoin_sig,
1381                 })
1382         }
1383
1384         /// Processes HTLCs which are pending waiting on random forward delay.
1385         ///
1386         /// Should only really ever be called in response to an PendingHTLCsForwardable event.
1387         /// Will likely generate further events.
1388         pub fn process_pending_htlc_forwards(&self) {
1389                 let _ = self.total_consistency_lock.read().unwrap();
1390
1391                 let mut new_events = Vec::new();
1392                 let mut failed_forwards = Vec::new();
1393                 {
1394                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1395                         let channel_state = channel_state_lock.borrow_parts();
1396
1397                         if cfg!(not(feature = "fuzztarget")) && Instant::now() < *channel_state.next_forward {
1398                                 return;
1399                         }
1400
1401                         for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1402                                 if short_chan_id != 0 {
1403                                         let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1404                                                 Some(chan_id) => chan_id.clone(),
1405                                                 None => {
1406                                                         failed_forwards.reserve(pending_forwards.len());
1407                                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1408                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1409                                                                         short_channel_id: prev_short_channel_id,
1410                                                                         htlc_id: prev_htlc_id,
1411                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1412                                                                 });
1413                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
1414                                                         }
1415                                                         continue;
1416                                                 }
1417                                         };
1418                                         let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();
1419
1420                                         let mut add_htlc_msgs = Vec::new();
1421                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1422                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1423                                                         short_channel_id: prev_short_channel_id,
1424                                                         htlc_id: prev_htlc_id,
1425                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1426                                                 });
1427                                                 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()) {
1428                                                         Err(_e) => {
1429                                                                 let chan_update = self.get_channel_update(forward_chan).unwrap();
1430                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x1000 | 7, Some(chan_update)));
1431                                                                 continue;
1432                                                         },
1433                                                         Ok(update_add) => {
1434                                                                 match update_add {
1435                                                                         Some(msg) => { add_htlc_msgs.push(msg); },
1436                                                                         None => {
1437                                                                                 // Nothing to do here...we're waiting on a remote
1438                                                                                 // revoke_and_ack before we can add anymore HTLCs. The Channel
1439                                                                                 // will automatically handle building the update_add_htlc and
1440                                                                                 // commitment_signed messages when we can.
1441                                                                                 // TODO: Do some kind of timer to set the channel as !is_live()
1442                                                                                 // as we don't really want others relying on us relaying through
1443                                                                                 // this channel currently :/.
1444                                                                         }
1445                                                                 }
1446                                                         }
1447                                                 }
1448                                         }
1449
1450                                         if !add_htlc_msgs.is_empty() {
1451                                                 let (commitment_msg, monitor) = match forward_chan.send_commitment() {
1452                                                         Ok(res) => res,
1453                                                         Err(e) => {
1454                                                                 if let ChannelError::Ignore(_) = e {
1455                                                                         panic!("Stated return value requirements in send_commitment() were not met");
1456                                                                 }
1457                                                                 //TODO: Handle...this is bad!
1458                                                                 continue;
1459                                                         },
1460                                                 };
1461                                                 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
1462                                                         unimplemented!();
1463                                                 }
1464                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1465                                                         node_id: forward_chan.get_their_node_id(),
1466                                                         updates: msgs::CommitmentUpdate {
1467                                                                 update_add_htlcs: add_htlc_msgs,
1468                                                                 update_fulfill_htlcs: Vec::new(),
1469                                                                 update_fail_htlcs: Vec::new(),
1470                                                                 update_fail_malformed_htlcs: Vec::new(),
1471                                                                 update_fee: None,
1472                                                                 commitment_signed: commitment_msg,
1473                                                         },
1474                                                 });
1475                                         }
1476                                 } else {
1477                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1478                                                 let prev_hop_data = HTLCPreviousHopData {
1479                                                         short_channel_id: prev_short_channel_id,
1480                                                         htlc_id: prev_htlc_id,
1481                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1482                                                 };
1483                                                 match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
1484                                                         hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(prev_hop_data),
1485                                                         hash_map::Entry::Vacant(entry) => { entry.insert(vec![prev_hop_data]); },
1486                                                 };
1487                                                 new_events.push(events::Event::PaymentReceived {
1488                                                         payment_hash: forward_info.payment_hash,
1489                                                         amt: forward_info.amt_to_forward,
1490                                                 });
1491                                         }
1492                                 }
1493                         }
1494                 }
1495
1496                 for (htlc_source, payment_hash, failure_code, update) in failed_forwards.drain(..) {
1497                         match update {
1498                                 None => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code, data: Vec::new() }),
1499                                 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() }),
1500                         };
1501                 }
1502
1503                 if new_events.is_empty() { return }
1504                 let mut events = self.pending_events.lock().unwrap();
1505                 events.append(&mut new_events);
1506         }
1507
1508         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
1509         /// after a PaymentReceived event.
1510         /// expected_value is the value you expected the payment to be for (not the amount it actually
1511         /// was for from the PaymentReceived event).
1512         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash, expected_value: u64) -> bool {
1513                 let _ = self.total_consistency_lock.read().unwrap();
1514
1515                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1516                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(payment_hash);
1517                 if let Some(mut sources) = removed_source {
1518                         for htlc_with_hash in sources.drain(..) {
1519                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1520                                 self.fail_htlc_backwards_internal(channel_state.take().unwrap(),
1521                                                 HTLCSource::PreviousHopData(htlc_with_hash), payment_hash,
1522                                                 HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: byte_utils::be64_to_array(expected_value).to_vec() });
1523                         }
1524                         true
1525                 } else { false }
1526         }
1527
1528         /// Fails an HTLC backwards to the sender of it to us.
1529         /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
1530         /// There are several callsites that do stupid things like loop over a list of payment_hashes
1531         /// to fail and take the channel_state lock for each iteration (as we take ownership and may
1532         /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
1533         /// still-available channels.
1534         fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
1535                 match source {
1536                         HTLCSource::OutboundRoute { ref route, .. } => {
1537                                 log_trace!(self, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1538                                 mem::drop(channel_state_lock);
1539                                 match &onion_error {
1540                                         &HTLCFailReason::ErrorPacket { ref err } => {
1541 #[cfg(test)]
1542                                                 let (channel_update, payment_retryable, onion_error_code) = self.process_onion_failure(&source, err.data.clone());
1543 #[cfg(not(test))]
1544                                                 let (channel_update, payment_retryable, _) = self.process_onion_failure(&source, err.data.clone());
1545                                                 // TODO: If we decided to blame ourselves (or one of our channels) in
1546                                                 // process_onion_failure we should close that channel as it implies our
1547                                                 // next-hop is needlessly blaming us!
1548                                                 if let Some(update) = channel_update {
1549                                                         self.channel_state.lock().unwrap().pending_msg_events.push(
1550                                                                 events::MessageSendEvent::PaymentFailureNetworkUpdate {
1551                                                                         update,
1552                                                                 }
1553                                                         );
1554                                                 }
1555                                                 self.pending_events.lock().unwrap().push(
1556                                                         events::Event::PaymentFailed {
1557                                                                 payment_hash: payment_hash.clone(),
1558                                                                 rejected_by_dest: !payment_retryable,
1559 #[cfg(test)]
1560                                                                 error_code: onion_error_code
1561                                                         }
1562                                                 );
1563                                         },
1564                                         &HTLCFailReason::Reason {
1565 #[cfg(test)]
1566                                                         ref failure_code,
1567                                                         .. } => {
1568                                                 // we get a fail_malformed_htlc from the first hop
1569                                                 // TODO: We'd like to generate a PaymentFailureNetworkUpdate for temporary
1570                                                 // failures here, but that would be insufficient as Router::get_route
1571                                                 // generally ignores its view of our own channels as we provide them via
1572                                                 // ChannelDetails.
1573                                                 // TODO: For non-temporary failures, we really should be closing the
1574                                                 // channel here as we apparently can't relay through them anyway.
1575                                                 self.pending_events.lock().unwrap().push(
1576                                                         events::Event::PaymentFailed {
1577                                                                 payment_hash: payment_hash.clone(),
1578                                                                 rejected_by_dest: route.hops.len() == 1,
1579 #[cfg(test)]
1580                                                                 error_code: Some(*failure_code),
1581                                                         }
1582                                                 );
1583                                         }
1584                                 }
1585                         },
1586                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
1587                                 let err_packet = match onion_error {
1588                                         HTLCFailReason::Reason { failure_code, data } => {
1589                                                 log_trace!(self, "Failing HTLC with payment_hash {} backwards from us with code {}", log_bytes!(payment_hash.0), failure_code);
1590                                                 let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1591                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1592                                         },
1593                                         HTLCFailReason::ErrorPacket { err } => {
1594                                                 log_trace!(self, "Failing HTLC with payment_hash {} backwards with pre-built ErrorPacket", log_bytes!(payment_hash.0));
1595                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1596                                         }
1597                                 };
1598
1599                                 let channel_state = channel_state_lock.borrow_parts();
1600
1601                                 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1602                                         Some(chan_id) => chan_id.clone(),
1603                                         None => return
1604                                 };
1605
1606                                 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1607                                 match chan.get_update_fail_htlc_and_commit(htlc_id, err_packet) {
1608                                         Ok(Some((msg, commitment_msg, chan_monitor))) => {
1609                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1610                                                         unimplemented!();
1611                                                 }
1612                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1613                                                         node_id: chan.get_their_node_id(),
1614                                                         updates: msgs::CommitmentUpdate {
1615                                                                 update_add_htlcs: Vec::new(),
1616                                                                 update_fulfill_htlcs: Vec::new(),
1617                                                                 update_fail_htlcs: vec![msg],
1618                                                                 update_fail_malformed_htlcs: Vec::new(),
1619                                                                 update_fee: None,
1620                                                                 commitment_signed: commitment_msg,
1621                                                         },
1622                                                 });
1623                                         },
1624                                         Ok(None) => {},
1625                                         Err(_e) => {
1626                                                 //TODO: Do something with e?
1627                                                 return;
1628                                         },
1629                                 }
1630                         },
1631                 }
1632         }
1633
1634         /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1635         /// generating message events for the net layer to claim the payment, if possible. Thus, you
1636         /// should probably kick the net layer to go send messages if this returns true!
1637         ///
1638         /// May panic if called except in response to a PaymentReceived event.
1639         pub fn claim_funds(&self, payment_preimage: PaymentPreimage) -> bool {
1640                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1641
1642                 let _ = self.total_consistency_lock.read().unwrap();
1643
1644                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1645                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&payment_hash);
1646                 if let Some(mut sources) = removed_source {
1647                         for htlc_with_hash in sources.drain(..) {
1648                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1649                                 self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_preimage);
1650                         }
1651                         true
1652                 } else { false }
1653         }
1654         fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_preimage: PaymentPreimage) {
1655                 match source {
1656                         HTLCSource::OutboundRoute { .. } => {
1657                                 mem::drop(channel_state_lock);
1658                                 let mut pending_events = self.pending_events.lock().unwrap();
1659                                 pending_events.push(events::Event::PaymentSent {
1660                                         payment_preimage
1661                                 });
1662                         },
1663                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, .. }) => {
1664                                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1665                                 let channel_state = channel_state_lock.borrow_parts();
1666
1667                                 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1668                                         Some(chan_id) => chan_id.clone(),
1669                                         None => {
1670                                                 // TODO: There is probably a channel manager somewhere that needs to
1671                                                 // learn the preimage as the channel already hit the chain and that's
1672                                                 // why its missing.
1673                                                 return
1674                                         }
1675                                 };
1676
1677                                 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1678                                 match chan.get_update_fulfill_htlc_and_commit(htlc_id, payment_preimage) {
1679                                         Ok((msgs, monitor_option)) => {
1680                                                 if let Some(chan_monitor) = monitor_option {
1681                                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1682                                                                 unimplemented!();// but def dont push the event...
1683                                                         }
1684                                                 }
1685                                                 if let Some((msg, commitment_signed)) = msgs {
1686                                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1687                                                                 node_id: chan.get_their_node_id(),
1688                                                                 updates: msgs::CommitmentUpdate {
1689                                                                         update_add_htlcs: Vec::new(),
1690                                                                         update_fulfill_htlcs: vec![msg],
1691                                                                         update_fail_htlcs: Vec::new(),
1692                                                                         update_fail_malformed_htlcs: Vec::new(),
1693                                                                         update_fee: None,
1694                                                                         commitment_signed,
1695                                                                 }
1696                                                         });
1697                                                 }
1698                                         },
1699                                         Err(_e) => {
1700                                                 // TODO: There is probably a channel manager somewhere that needs to
1701                                                 // learn the preimage as the channel may be about to hit the chain.
1702                                                 //TODO: Do something with e?
1703                                                 return
1704                                         },
1705                                 }
1706                         },
1707                 }
1708         }
1709
1710         /// Gets the node_id held by this ChannelManager
1711         pub fn get_our_node_id(&self) -> PublicKey {
1712                 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
1713         }
1714
1715         /// Used to restore channels to normal operation after a
1716         /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
1717         /// operation.
1718         pub fn test_restore_channel_monitor(&self) {
1719                 let mut close_results = Vec::new();
1720                 let mut htlc_forwards = Vec::new();
1721                 let mut htlc_failures = Vec::new();
1722                 let _ = self.total_consistency_lock.read().unwrap();
1723
1724                 {
1725                         let mut channel_lock = self.channel_state.lock().unwrap();
1726                         let channel_state = channel_lock.borrow_parts();
1727                         let short_to_id = channel_state.short_to_id;
1728                         let pending_msg_events = channel_state.pending_msg_events;
1729                         channel_state.by_id.retain(|_, channel| {
1730                                 if channel.is_awaiting_monitor_update() {
1731                                         let chan_monitor = channel.channel_monitor();
1732                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1733                                                 match e {
1734                                                         ChannelMonitorUpdateErr::PermanentFailure => {
1735                                                                 // TODO: There may be some pending HTLCs that we intended to fail
1736                                                                 // backwards when a monitor update failed. We should make sure
1737                                                                 // knowledge of those gets moved into the appropriate in-memory
1738                                                                 // ChannelMonitor and they get failed backwards once we get
1739                                                                 // on-chain confirmations.
1740                                                                 // Note I think #198 addresses this, so once its merged a test
1741                                                                 // should be written.
1742                                                                 if let Some(short_id) = channel.get_short_channel_id() {
1743                                                                         short_to_id.remove(&short_id);
1744                                                                 }
1745                                                                 close_results.push(channel.force_shutdown());
1746                                                                 if let Ok(update) = self.get_channel_update(&channel) {
1747                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1748                                                                                 msg: update
1749                                                                         });
1750                                                                 }
1751                                                                 false
1752                                                         },
1753                                                         ChannelMonitorUpdateErr::TemporaryFailure => true,
1754                                                 }
1755                                         } else {
1756                                                 let (raa, commitment_update, order, pending_forwards, mut pending_failures) = channel.monitor_updating_restored();
1757                                                 if !pending_forwards.is_empty() {
1758                                                         htlc_forwards.push((channel.get_short_channel_id().expect("We can't have pending forwards before funding confirmation"), pending_forwards));
1759                                                 }
1760                                                 htlc_failures.append(&mut pending_failures);
1761
1762                                                 macro_rules! handle_cs { () => {
1763                                                         if let Some(update) = commitment_update {
1764                                                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1765                                                                         node_id: channel.get_their_node_id(),
1766                                                                         updates: update,
1767                                                                 });
1768                                                         }
1769                                                 } }
1770                                                 macro_rules! handle_raa { () => {
1771                                                         if let Some(revoke_and_ack) = raa {
1772                                                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
1773                                                                         node_id: channel.get_their_node_id(),
1774                                                                         msg: revoke_and_ack,
1775                                                                 });
1776                                                         }
1777                                                 } }
1778                                                 match order {
1779                                                         RAACommitmentOrder::CommitmentFirst => {
1780                                                                 handle_cs!();
1781                                                                 handle_raa!();
1782                                                         },
1783                                                         RAACommitmentOrder::RevokeAndACKFirst => {
1784                                                                 handle_raa!();
1785                                                                 handle_cs!();
1786                                                         },
1787                                                 }
1788                                                 true
1789                                         }
1790                                 } else { true }
1791                         });
1792                 }
1793
1794                 for failure in htlc_failures.drain(..) {
1795                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
1796                 }
1797                 self.forward_htlcs(&mut htlc_forwards[..]);
1798
1799                 for res in close_results.drain(..) {
1800                         self.finish_force_close_channel(res);
1801                 }
1802         }
1803
1804         fn internal_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
1805                 if msg.chain_hash != self.genesis_hash {
1806                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash", msg.temporary_channel_id.clone()));
1807                 }
1808
1809                 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)
1810                         .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
1811                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1812                 let channel_state = channel_state_lock.borrow_parts();
1813                 match channel_state.by_id.entry(channel.channel_id()) {
1814                         hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!", msg.temporary_channel_id.clone())),
1815                         hash_map::Entry::Vacant(entry) => {
1816                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
1817                                         node_id: their_node_id.clone(),
1818                                         msg: channel.get_accept_channel(),
1819                                 });
1820                                 entry.insert(channel);
1821                         }
1822                 }
1823                 Ok(())
1824         }
1825
1826         fn internal_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
1827                 let (value, output_script, user_id) = {
1828                         let mut channel_lock = self.channel_state.lock().unwrap();
1829                         let channel_state = channel_lock.borrow_parts();
1830                         match channel_state.by_id.entry(msg.temporary_channel_id) {
1831                                 hash_map::Entry::Occupied(mut chan) => {
1832                                         if chan.get().get_their_node_id() != *their_node_id {
1833                                                 //TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
1834                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1835                                         }
1836                                         try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration), channel_state, chan);
1837                                         (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
1838                                 },
1839                                 //TODO: same as above
1840                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1841                         }
1842                 };
1843                 let mut pending_events = self.pending_events.lock().unwrap();
1844                 pending_events.push(events::Event::FundingGenerationReady {
1845                         temporary_channel_id: msg.temporary_channel_id,
1846                         channel_value_satoshis: value,
1847                         output_script: output_script,
1848                         user_channel_id: user_id,
1849                 });
1850                 Ok(())
1851         }
1852
1853         fn internal_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
1854                 let ((funding_msg, monitor_update), chan) = {
1855                         let mut channel_lock = self.channel_state.lock().unwrap();
1856                         let channel_state = channel_lock.borrow_parts();
1857                         match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
1858                                 hash_map::Entry::Occupied(mut chan) => {
1859                                         if chan.get().get_their_node_id() != *their_node_id {
1860                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1861                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1862                                         }
1863                                         (try_chan_entry!(self, chan.get_mut().funding_created(msg), channel_state, chan), chan.remove())
1864                                 },
1865                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1866                         }
1867                 };
1868                 // Because we have exclusive ownership of the channel here we can release the channel_state
1869                 // lock before add_update_monitor
1870                 if let Err(_e) = self.monitor.add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) {
1871                         unimplemented!();
1872                 }
1873                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1874                 let channel_state = channel_state_lock.borrow_parts();
1875                 match channel_state.by_id.entry(funding_msg.channel_id) {
1876                         hash_map::Entry::Occupied(_) => {
1877                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id", funding_msg.channel_id))
1878                         },
1879                         hash_map::Entry::Vacant(e) => {
1880                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
1881                                         node_id: their_node_id.clone(),
1882                                         msg: funding_msg,
1883                                 });
1884                                 e.insert(chan);
1885                         }
1886                 }
1887                 Ok(())
1888         }
1889
1890         fn internal_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
1891                 let (funding_txo, user_id) = {
1892                         let mut channel_lock = self.channel_state.lock().unwrap();
1893                         let channel_state = channel_lock.borrow_parts();
1894                         match channel_state.by_id.entry(msg.channel_id) {
1895                                 hash_map::Entry::Occupied(mut chan) => {
1896                                         if chan.get().get_their_node_id() != *their_node_id {
1897                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1898                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1899                                         }
1900                                         let chan_monitor = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
1901                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1902                                                 unimplemented!();
1903                                         }
1904                                         (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())
1905                                 },
1906                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1907                         }
1908                 };
1909                 let mut pending_events = self.pending_events.lock().unwrap();
1910                 pending_events.push(events::Event::FundingBroadcastSafe {
1911                         funding_txo: funding_txo,
1912                         user_channel_id: user_id,
1913                 });
1914                 Ok(())
1915         }
1916
1917         fn internal_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), MsgHandleErrInternal> {
1918                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1919                 let channel_state = channel_state_lock.borrow_parts();
1920                 match channel_state.by_id.entry(msg.channel_id) {
1921                         hash_map::Entry::Occupied(mut chan) => {
1922                                 if chan.get().get_their_node_id() != *their_node_id {
1923                                         //TODO: here and below MsgHandleErrInternal, #153 case
1924                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1925                                 }
1926                                 try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
1927                                 if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
1928                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
1929                                                 node_id: their_node_id.clone(),
1930                                                 msg: announcement_sigs,
1931                                         });
1932                                 }
1933                                 Ok(())
1934                         },
1935                         hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1936                 }
1937         }
1938
1939         fn internal_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
1940                 let (mut dropped_htlcs, chan_option) = {
1941                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1942                         let channel_state = channel_state_lock.borrow_parts();
1943
1944                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1945                                 hash_map::Entry::Occupied(mut chan_entry) => {
1946                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1947                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1948                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1949                                         }
1950                                         let (shutdown, closing_signed, dropped_htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg), channel_state, chan_entry);
1951                                         if let Some(msg) = shutdown {
1952                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
1953                                                         node_id: their_node_id.clone(),
1954                                                         msg,
1955                                                 });
1956                                         }
1957                                         if let Some(msg) = closing_signed {
1958                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1959                                                         node_id: their_node_id.clone(),
1960                                                         msg,
1961                                                 });
1962                                         }
1963                                         if chan_entry.get().is_shutdown() {
1964                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1965                                                         channel_state.short_to_id.remove(&short_id);
1966                                                 }
1967                                                 (dropped_htlcs, Some(chan_entry.remove_entry().1))
1968                                         } else { (dropped_htlcs, None) }
1969                                 },
1970                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1971                         }
1972                 };
1973                 for htlc_source in dropped_htlcs.drain(..) {
1974                         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() });
1975                 }
1976                 if let Some(chan) = chan_option {
1977                         if let Ok(update) = self.get_channel_update(&chan) {
1978                                 let mut channel_state = self.channel_state.lock().unwrap();
1979                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1980                                         msg: update
1981                                 });
1982                         }
1983                 }
1984                 Ok(())
1985         }
1986
1987         fn internal_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
1988                 let (tx, chan_option) = {
1989                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1990                         let channel_state = channel_state_lock.borrow_parts();
1991                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1992                                 hash_map::Entry::Occupied(mut chan_entry) => {
1993                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1994                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1995                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1996                                         }
1997                                         let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg), channel_state, chan_entry);
1998                                         if let Some(msg) = closing_signed {
1999                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2000                                                         node_id: their_node_id.clone(),
2001                                                         msg,
2002                                                 });
2003                                         }
2004                                         if tx.is_some() {
2005                                                 // We're done with this channel, we've got a signed closing transaction and
2006                                                 // will send the closing_signed back to the remote peer upon return. This
2007                                                 // also implies there are no pending HTLCs left on the channel, so we can
2008                                                 // fully delete it from tracking (the channel monitor is still around to
2009                                                 // watch for old state broadcasts)!
2010                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2011                                                         channel_state.short_to_id.remove(&short_id);
2012                                                 }
2013                                                 (tx, Some(chan_entry.remove_entry().1))
2014                                         } else { (tx, None) }
2015                                 },
2016                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2017                         }
2018                 };
2019                 if let Some(broadcast_tx) = tx {
2020                         self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
2021                 }
2022                 if let Some(chan) = chan_option {
2023                         if let Ok(update) = self.get_channel_update(&chan) {
2024                                 let mut channel_state = self.channel_state.lock().unwrap();
2025                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2026                                         msg: update
2027                                 });
2028                         }
2029                 }
2030                 Ok(())
2031         }
2032
2033         fn internal_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
2034                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
2035                 //determine the state of the payment based on our response/if we forward anything/the time
2036                 //we take to respond. We should take care to avoid allowing such an attack.
2037                 //
2038                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
2039                 //us repeatedly garbled in different ways, and compare our error messages, which are
2040                 //encrypted with the same key. Its not immediately obvious how to usefully exploit that,
2041                 //but we should prevent it anyway.
2042
2043                 let (mut pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
2044                 let channel_state = channel_state_lock.borrow_parts();
2045
2046                 match channel_state.by_id.entry(msg.channel_id) {
2047                         hash_map::Entry::Occupied(mut chan) => {
2048                                 if chan.get().get_their_node_id() != *their_node_id {
2049                                         //TODO: here MsgHandleErrInternal, #153 case
2050                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2051                                 }
2052                                 if !chan.get().is_usable() {
2053                                         // If the update_add is completely bogus, the call will Err and we will close,
2054                                         // but if we've sent a shutdown and they haven't acknowledged it yet, we just
2055                                         // want to reject the new HTLC and fail it backwards instead of forwarding.
2056                                         if let PendingHTLCStatus::Forward(PendingForwardHTLCInfo { incoming_shared_secret, .. }) = pending_forward_info {
2057                                                 let chan_update = self.get_channel_update(chan.get());
2058                                                 pending_forward_info = PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
2059                                                         channel_id: msg.channel_id,
2060                                                         htlc_id: msg.htlc_id,
2061                                                         reason: if let Ok(update) = chan_update {
2062                                                                 // TODO: Note that |20 is defined as "channel FROM the processing
2063                                                                 // node has been disabled" (emphasis mine), which seems to imply
2064                                                                 // that we can't return |20 for an inbound channel being disabled.
2065                                                                 // This probably needs a spec update but should definitely be
2066                                                                 // allowed.
2067                                                                 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x1000|20, &{
2068                                                                         let mut res = Vec::with_capacity(8 + 128);
2069                                                                         res.extend_from_slice(&byte_utils::be16_to_array(update.contents.flags));
2070                                                                         res.extend_from_slice(&update.encode_with_len()[..]);
2071                                                                         res
2072                                                                 }[..])
2073                                                         } else {
2074                                                                 // This can only happen if the channel isn't in the fully-funded
2075                                                                 // state yet, implying our counterparty is trying to route payments
2076                                                                 // over the channel back to themselves (cause no one else should
2077                                                                 // know the short_id is a lightning channel yet). We should have no
2078                                                                 // problem just calling this unknown_next_peer
2079                                                                 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x4000|10, &[])
2080                                                         },
2081                                                 }));
2082                                         }
2083                                 }
2084                                 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info), channel_state, chan);
2085                         },
2086                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2087                 }
2088                 Ok(())
2089         }
2090
2091         fn internal_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
2092                 let mut channel_lock = self.channel_state.lock().unwrap();
2093                 let htlc_source = {
2094                         let channel_state = channel_lock.borrow_parts();
2095                         match channel_state.by_id.entry(msg.channel_id) {
2096                                 hash_map::Entry::Occupied(mut chan) => {
2097                                         if chan.get().get_their_node_id() != *their_node_id {
2098                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2099                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2100                                         }
2101                                         try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), channel_state, chan)
2102                                 },
2103                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2104                         }
2105                 };
2106                 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
2107                 Ok(())
2108         }
2109
2110         // Process failure we got back from upstream on a payment we sent. Returns update and a boolean
2111         // indicating that the payment itself failed
2112         fn process_onion_failure(&self, htlc_source: &HTLCSource, mut packet_decrypted: Vec<u8>) -> (Option<msgs::HTLCFailChannelUpdate>, bool, Option<u16>) {
2113                 if let &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } = htlc_source {
2114
2115                         let mut res = None;
2116                         let mut htlc_msat = *first_hop_htlc_msat;
2117                         let mut error_code_ret = None;
2118                         let mut next_route_hop_ix = 0;
2119                         let mut is_from_final_node = false;
2120
2121                         // Handle packed channel/node updates for passing back for the route handler
2122                         Self::construct_onion_keys_callback(&self.secp_ctx, route, session_priv, |shared_secret, _, _, route_hop| {
2123                                 next_route_hop_ix += 1;
2124                                 if res.is_some() { return; }
2125
2126                                 let amt_to_forward = htlc_msat - route_hop.fee_msat;
2127                                 htlc_msat = amt_to_forward;
2128
2129                                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret[..]);
2130
2131                                 let mut decryption_tmp = Vec::with_capacity(packet_decrypted.len());
2132                                 decryption_tmp.resize(packet_decrypted.len(), 0);
2133                                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
2134                                 chacha.process(&packet_decrypted, &mut decryption_tmp[..]);
2135                                 packet_decrypted = decryption_tmp;
2136
2137                                 is_from_final_node = route.hops.last().unwrap().pubkey == route_hop.pubkey;
2138
2139                                 if let Ok(err_packet) = msgs::DecodedOnionErrorPacket::read(&mut Cursor::new(&packet_decrypted)) {
2140                                         let um = ChannelManager::gen_um_from_shared_secret(&shared_secret[..]);
2141                                         let mut hmac = HmacEngine::<Sha256>::new(&um);
2142                                         hmac.input(&err_packet.encode()[32..]);
2143
2144                                         if crypto::util::fixed_time_eq(&Hmac::from_engine(hmac).into_inner(), &err_packet.hmac) {
2145                                                 if let Some(error_code_slice) = err_packet.failuremsg.get(0..2) {
2146                                                         const PERM: u16 = 0x4000;
2147                                                         const NODE: u16 = 0x2000;
2148                                                         const UPDATE: u16 = 0x1000;
2149
2150                                                         let error_code = byte_utils::slice_to_be16(&error_code_slice);
2151                                                         error_code_ret = Some(error_code);
2152
2153                                                         let (debug_field, debug_field_size) = errors::get_onion_debug_field(error_code);
2154
2155                                                         // indicate that payment parameter has failed and no need to
2156                                                         // update Route object
2157                                                         let payment_failed = (match error_code & 0xff {
2158                                                                 15|16|17|18|19 => true,
2159                                                                 _ => false,
2160                                                         } && is_from_final_node) // PERM bit observed below even this error is from the intermediate nodes
2161                                                         || error_code == 21; // Special case error 21 as the Route object is bogus, TODO: Maybe fail the node if the CLTV was reasonable?
2162
2163                                                         let mut fail_channel_update = None;
2164
2165                                                         if error_code & NODE == NODE {
2166                                                                 fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure { node_id: route_hop.pubkey, is_permanent: error_code & PERM == PERM });
2167                                                         }
2168                                                         else if error_code & PERM == PERM {
2169                                                                 fail_channel_update = if payment_failed {None} else {Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
2170                                                                         short_channel_id: route.hops[next_route_hop_ix - if next_route_hop_ix == route.hops.len() { 1 } else { 0 }].short_channel_id,
2171                                                                         is_permanent: true,
2172                                                                 })};
2173                                                         }
2174                                                         else if error_code & UPDATE == UPDATE {
2175                                                                 if let Some(update_len_slice) = err_packet.failuremsg.get(debug_field_size+2..debug_field_size+4) {
2176                                                                         let update_len = byte_utils::slice_to_be16(&update_len_slice) as usize;
2177                                                                         if let Some(update_slice) = err_packet.failuremsg.get(debug_field_size + 4..debug_field_size + 4 + update_len) {
2178                                                                                 if let Ok(chan_update) = msgs::ChannelUpdate::read(&mut Cursor::new(&update_slice)) {
2179                                                                                         // if channel_update should NOT have caused the failure:
2180                                                                                         // MAY treat the channel_update as invalid.
2181                                                                                         let is_chan_update_invalid = match error_code & 0xff {
2182                                                                                                 7 => false,
2183                                                                                                 11 => amt_to_forward > chan_update.contents.htlc_minimum_msat,
2184                                                                                                 12 => {
2185                                                                                                         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) });
2186                                                                                                         new_fee.is_some() && route_hop.fee_msat >= new_fee.unwrap()
2187                                                                                                 }
2188                                                                                                 13 => route_hop.cltv_expiry_delta as u16 >= chan_update.contents.cltv_expiry_delta,
2189                                                                                                 14 => false, // expiry_too_soon; always valid?
2190                                                                                                 20 => chan_update.contents.flags & 2 == 0,
2191                                                                                                 _ => false, // unknown error code; take channel_update as valid
2192                                                                                         };
2193                                                                                         fail_channel_update = if is_chan_update_invalid {
2194                                                                                                 // This probably indicates the node which forwarded
2195                                                                                                 // to the node in question corrupted something.
2196                                                                                                 Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
2197                                                                                                         short_channel_id: route_hop.short_channel_id,
2198                                                                                                         is_permanent: true,
2199                                                                                                 })
2200                                                                                         } else {
2201                                                                                                 Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {
2202                                                                                                         msg: chan_update,
2203                                                                                                 })
2204                                                                                         };
2205                                                                                 }
2206                                                                         }
2207                                                                 }
2208                                                                 if fail_channel_update.is_none() {
2209                                                                         // They provided an UPDATE which was obviously bogus, not worth
2210                                                                         // trying to relay through them anymore.
2211                                                                         fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2212                                                                                 node_id: route_hop.pubkey,
2213                                                                                 is_permanent: true,
2214                                                                         });
2215                                                                 }
2216                                                         } else if !payment_failed {
2217                                                                 // We can't understand their error messages and they failed to
2218                                                                 // forward...they probably can't understand our forwards so its
2219                                                                 // really not worth trying any further.
2220                                                                 fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2221                                                                         node_id: route_hop.pubkey,
2222                                                                         is_permanent: true,
2223                                                                 });
2224                                                         }
2225
2226                                                         // TODO: Here (and a few other places) we assume that BADONION errors
2227                                                         // are always "sourced" from the node previous to the one which failed
2228                                                         // to decode the onion.
2229                                                         res = Some((fail_channel_update, !(error_code & PERM == PERM && is_from_final_node)));
2230
2231                                                         let (description, title) = errors::get_onion_error_description(error_code);
2232                                                         if debug_field_size > 0 && err_packet.failuremsg.len() >= 4 + debug_field_size {
2233                                                                 log_warn!(self, "Onion Error[{}({:#x}) {}({})] {}", title, error_code, debug_field, log_bytes!(&err_packet.failuremsg[4..4+debug_field_size]), description);
2234                                                         }
2235                                                         else {
2236                                                                 log_warn!(self, "Onion Error[{}({:#x})] {}", title, error_code, description);
2237                                                         }
2238                                                 } else {
2239                                                         // Useless packet that we can't use but it passed HMAC, so it
2240                                                         // definitely came from the peer in question
2241                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2242                                                                 node_id: route_hop.pubkey,
2243                                                                 is_permanent: true,
2244                                                         }), !is_from_final_node));
2245                                                 }
2246                                         }
2247                                 }
2248                         }).expect("Route that we sent via spontaneously grew invalid keys in the middle of it?");
2249                         if let Some((channel_update, payment_retryable)) = res {
2250                                 (channel_update, payment_retryable, error_code_ret)
2251                         } else {
2252                                 // only not set either packet unparseable or hmac does not match with any
2253                                 // payment not retryable only when garbage is from the final node
2254                                 (None, !is_from_final_node, None)
2255                         }
2256                 } else { unreachable!(); }
2257         }
2258
2259         fn internal_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
2260                 let mut channel_lock = self.channel_state.lock().unwrap();
2261                 let channel_state = channel_lock.borrow_parts();
2262                 match channel_state.by_id.entry(msg.channel_id) {
2263                         hash_map::Entry::Occupied(mut chan) => {
2264                                 if chan.get().get_their_node_id() != *their_node_id {
2265                                         //TODO: here and below MsgHandleErrInternal, #153 case
2266                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2267                                 }
2268                                 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::ErrorPacket { err: msg.reason.clone() }), channel_state, chan);
2269                         },
2270                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2271                 }
2272                 Ok(())
2273         }
2274
2275         fn internal_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
2276                 let mut channel_lock = self.channel_state.lock().unwrap();
2277                 let channel_state = channel_lock.borrow_parts();
2278                 match channel_state.by_id.entry(msg.channel_id) {
2279                         hash_map::Entry::Occupied(mut chan) => {
2280                                 if chan.get().get_their_node_id() != *their_node_id {
2281                                         //TODO: here and below MsgHandleErrInternal, #153 case
2282                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2283                                 }
2284                                 if (msg.failure_code & 0x8000) == 0 {
2285                                         try_chan_entry!(self, Err(ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set")), channel_state, chan);
2286                                 }
2287                                 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);
2288                                 Ok(())
2289                         },
2290                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2291                 }
2292         }
2293
2294         fn internal_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
2295                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2296                 let channel_state = channel_state_lock.borrow_parts();
2297                 match channel_state.by_id.entry(msg.channel_id) {
2298                         hash_map::Entry::Occupied(mut chan) => {
2299                                 if chan.get().get_their_node_id() != *their_node_id {
2300                                         //TODO: here and below MsgHandleErrInternal, #153 case
2301                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2302                                 }
2303                                 let (revoke_and_ack, commitment_signed, closing_signed, chan_monitor) =
2304                                         try_chan_entry!(self, chan.get_mut().commitment_signed(&msg, &*self.fee_estimator), channel_state, chan);
2305                                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2306                                         return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, commitment_signed.is_some());
2307                                         //TODO: Rebroadcast closing_signed if present on monitor update restoration
2308                                 }
2309                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2310                                         node_id: their_node_id.clone(),
2311                                         msg: revoke_and_ack,
2312                                 });
2313                                 if let Some(msg) = commitment_signed {
2314                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2315                                                 node_id: their_node_id.clone(),
2316                                                 updates: msgs::CommitmentUpdate {
2317                                                         update_add_htlcs: Vec::new(),
2318                                                         update_fulfill_htlcs: Vec::new(),
2319                                                         update_fail_htlcs: Vec::new(),
2320                                                         update_fail_malformed_htlcs: Vec::new(),
2321                                                         update_fee: None,
2322                                                         commitment_signed: msg,
2323                                                 },
2324                                         });
2325                                 }
2326                                 if let Some(msg) = closing_signed {
2327                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2328                                                 node_id: their_node_id.clone(),
2329                                                 msg,
2330                                         });
2331                                 }
2332                                 Ok(())
2333                         },
2334                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2335                 }
2336         }
2337
2338         #[inline]
2339         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64)>)]) {
2340                 for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
2341                         let mut forward_event = None;
2342                         if !pending_forwards.is_empty() {
2343                                 let mut channel_state = self.channel_state.lock().unwrap();
2344                                 if channel_state.forward_htlcs.is_empty() {
2345                                         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));
2346                                         channel_state.next_forward = forward_event.unwrap();
2347                                 }
2348                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2349                                         match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
2350                                                 hash_map::Entry::Occupied(mut entry) => {
2351                                                         entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info });
2352                                                 },
2353                                                 hash_map::Entry::Vacant(entry) => {
2354                                                         entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info }));
2355                                                 }
2356                                         }
2357                                 }
2358                         }
2359                         match forward_event {
2360                                 Some(time) => {
2361                                         let mut pending_events = self.pending_events.lock().unwrap();
2362                                         pending_events.push(events::Event::PendingHTLCsForwardable {
2363                                                 time_forwardable: time
2364                                         });
2365                                 }
2366                                 None => {},
2367                         }
2368                 }
2369         }
2370
2371         fn internal_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
2372                 let (pending_forwards, mut pending_failures, short_channel_id) = {
2373                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2374                         let channel_state = channel_state_lock.borrow_parts();
2375                         match channel_state.by_id.entry(msg.channel_id) {
2376                                 hash_map::Entry::Occupied(mut chan) => {
2377                                         if chan.get().get_their_node_id() != *their_node_id {
2378                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2379                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2380                                         }
2381                                         let (commitment_update, pending_forwards, pending_failures, closing_signed, chan_monitor) =
2382                                                 try_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &*self.fee_estimator), channel_state, chan);
2383                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2384                                                 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, pending_forwards, pending_failures);
2385                                         }
2386                                         if let Some(updates) = commitment_update {
2387                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2388                                                         node_id: their_node_id.clone(),
2389                                                         updates,
2390                                                 });
2391                                         }
2392                                         if let Some(msg) = closing_signed {
2393                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2394                                                         node_id: their_node_id.clone(),
2395                                                         msg,
2396                                                 });
2397                                         }
2398                                         (pending_forwards, pending_failures, chan.get().get_short_channel_id().expect("RAA should only work on a short-id-available channel"))
2399                                 },
2400                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2401                         }
2402                 };
2403                 for failure in pending_failures.drain(..) {
2404                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2405                 }
2406                 self.forward_htlcs(&mut [(short_channel_id, pending_forwards)]);
2407
2408                 Ok(())
2409         }
2410
2411         fn internal_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2412                 let mut channel_lock = self.channel_state.lock().unwrap();
2413                 let channel_state = channel_lock.borrow_parts();
2414                 match channel_state.by_id.entry(msg.channel_id) {
2415                         hash_map::Entry::Occupied(mut chan) => {
2416                                 if chan.get().get_their_node_id() != *their_node_id {
2417                                         //TODO: here and below MsgHandleErrInternal, #153 case
2418                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2419                                 }
2420                                 try_chan_entry!(self, chan.get_mut().update_fee(&*self.fee_estimator, &msg), channel_state, chan);
2421                         },
2422                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2423                 }
2424                 Ok(())
2425         }
2426
2427         fn internal_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2428                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2429                 let channel_state = channel_state_lock.borrow_parts();
2430
2431                 match channel_state.by_id.entry(msg.channel_id) {
2432                         hash_map::Entry::Occupied(mut chan) => {
2433                                 if chan.get().get_their_node_id() != *their_node_id {
2434                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2435                                 }
2436                                 if !chan.get().is_usable() {
2437                                         return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Got an announcement_signatures before we were ready for it", action: Some(msgs::ErrorAction::IgnoreError)}));
2438                                 }
2439
2440                                 let our_node_id = self.get_our_node_id();
2441                                 let (announcement, our_bitcoin_sig) =
2442                                         try_chan_entry!(self, chan.get_mut().get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone()), channel_state, chan);
2443
2444                                 let were_node_one = announcement.node_id_1 == our_node_id;
2445                                 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
2446                                 if self.secp_ctx.verify(&msghash, &msg.node_signature, if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 }).is_err() ||
2447                                                 self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 }).is_err() {
2448                                         try_chan_entry!(self, Err(ChannelError::Close("Bad announcement_signatures node_signature")), channel_state, chan);
2449                                 }
2450
2451                                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2452
2453                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
2454                                         msg: msgs::ChannelAnnouncement {
2455                                                 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
2456                                                 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
2457                                                 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
2458                                                 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
2459                                                 contents: announcement,
2460                                         },
2461                                         update_msg: self.get_channel_update(chan.get()).unwrap(), // can only fail if we're not in a ready state
2462                                 });
2463                         },
2464                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2465                 }
2466                 Ok(())
2467         }
2468
2469         fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
2470                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2471                 let channel_state = channel_state_lock.borrow_parts();
2472
2473                 match channel_state.by_id.entry(msg.channel_id) {
2474                         hash_map::Entry::Occupied(mut chan) => {
2475                                 if chan.get().get_their_node_id() != *their_node_id {
2476                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2477                                 }
2478                                 let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, mut order, shutdown) =
2479                                         try_chan_entry!(self, chan.get_mut().channel_reestablish(msg), channel_state, chan);
2480                                 if let Some(monitor) = channel_monitor {
2481                                         if let Err(e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
2482                                                 // channel_reestablish doesn't guarantee the order it returns is sensical
2483                                                 // for the messages it returns, but if we're setting what messages to
2484                                                 // re-transmit on monitor update success, we need to make sure it is sane.
2485                                                 if revoke_and_ack.is_none() {
2486                                                         order = RAACommitmentOrder::CommitmentFirst;
2487                                                 }
2488                                                 if commitment_update.is_none() {
2489                                                         order = RAACommitmentOrder::RevokeAndACKFirst;
2490                                                 }
2491                                                 return_monitor_err!(self, e, channel_state, chan, order);
2492                                                 //TODO: Resend the funding_locked if needed once we get the monitor running again
2493                                         }
2494                                 }
2495                                 if let Some(msg) = funding_locked {
2496                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2497                                                 node_id: their_node_id.clone(),
2498                                                 msg
2499                                         });
2500                                 }
2501                                 macro_rules! send_raa { () => {
2502                                         if let Some(msg) = revoke_and_ack {
2503                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2504                                                         node_id: their_node_id.clone(),
2505                                                         msg
2506                                                 });
2507                                         }
2508                                 } }
2509                                 macro_rules! send_cu { () => {
2510                                         if let Some(updates) = commitment_update {
2511                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2512                                                         node_id: their_node_id.clone(),
2513                                                         updates
2514                                                 });
2515                                         }
2516                                 } }
2517                                 match order {
2518                                         RAACommitmentOrder::RevokeAndACKFirst => {
2519                                                 send_raa!();
2520                                                 send_cu!();
2521                                         },
2522                                         RAACommitmentOrder::CommitmentFirst => {
2523                                                 send_cu!();
2524                                                 send_raa!();
2525                                         },
2526                                 }
2527                                 if let Some(msg) = shutdown {
2528                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2529                                                 node_id: their_node_id.clone(),
2530                                                 msg,
2531                                         });
2532                                 }
2533                                 Ok(())
2534                         },
2535                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2536                 }
2537         }
2538
2539         /// Begin Update fee process. Allowed only on an outbound channel.
2540         /// If successful, will generate a UpdateHTLCs event, so you should probably poll
2541         /// PeerManager::process_events afterwards.
2542         /// Note: This API is likely to change!
2543         #[doc(hidden)]
2544         pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u64) -> Result<(), APIError> {
2545                 let _ = self.total_consistency_lock.read().unwrap();
2546                 let their_node_id;
2547                 let err: Result<(), _> = loop {
2548                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2549                         let channel_state = channel_state_lock.borrow_parts();
2550
2551                         match channel_state.by_id.entry(channel_id) {
2552                                 hash_map::Entry::Vacant(_) => return Err(APIError::APIMisuseError{err: "Failed to find corresponding channel"}),
2553                                 hash_map::Entry::Occupied(mut chan) => {
2554                                         if !chan.get().is_outbound() {
2555                                                 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel"});
2556                                         }
2557                                         if chan.get().is_awaiting_monitor_update() {
2558                                                 return Err(APIError::MonitorUpdateFailed);
2559                                         }
2560                                         if !chan.get().is_live() {
2561                                                 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected"});
2562                                         }
2563                                         their_node_id = chan.get().get_their_node_id();
2564                                         if let Some((update_fee, commitment_signed, chan_monitor)) =
2565                                                         break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw), channel_state, chan)
2566                                         {
2567                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2568                                                         unimplemented!();
2569                                                 }
2570                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2571                                                         node_id: chan.get().get_their_node_id(),
2572                                                         updates: msgs::CommitmentUpdate {
2573                                                                 update_add_htlcs: Vec::new(),
2574                                                                 update_fulfill_htlcs: Vec::new(),
2575                                                                 update_fail_htlcs: Vec::new(),
2576                                                                 update_fail_malformed_htlcs: Vec::new(),
2577                                                                 update_fee: Some(update_fee),
2578                                                                 commitment_signed,
2579                                                         },
2580                                                 });
2581                                         }
2582                                 },
2583                         }
2584                         return Ok(())
2585                 };
2586
2587                 match handle_error!(self, err, their_node_id) {
2588                         Ok(_) => unreachable!(),
2589                         Err(e) => {
2590                                 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
2591                                 } else {
2592                                         log_error!(self, "Got bad keys: {}!", e.err);
2593                                         let mut channel_state = self.channel_state.lock().unwrap();
2594                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
2595                                                 node_id: their_node_id,
2596                                                 action: e.action,
2597                                         });
2598                                 }
2599                                 Err(APIError::APIMisuseError { err: e.err })
2600                         },
2601                 }
2602         }
2603 }
2604
2605 impl events::MessageSendEventsProvider for ChannelManager {
2606         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
2607                 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2608                 // user to serialize a ChannelManager with pending events in it and lose those events on
2609                 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2610                 {
2611                         //TODO: This behavior should be documented.
2612                         for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2613                                 if let Some(preimage) = htlc_update.payment_preimage {
2614                                         log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2615                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2616                                 } else {
2617                                         log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2618                                         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() });
2619                                 }
2620                         }
2621                 }
2622
2623                 let mut ret = Vec::new();
2624                 let mut channel_state = self.channel_state.lock().unwrap();
2625                 mem::swap(&mut ret, &mut channel_state.pending_msg_events);
2626                 ret
2627         }
2628 }
2629
2630 impl events::EventsProvider for ChannelManager {
2631         fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
2632                 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2633                 // user to serialize a ChannelManager with pending events in it and lose those events on
2634                 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2635                 {
2636                         //TODO: This behavior should be documented.
2637                         for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2638                                 if let Some(preimage) = htlc_update.payment_preimage {
2639                                         log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2640                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2641                                 } else {
2642                                         log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2643                                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
2644                                 }
2645                         }
2646                 }
2647
2648                 let mut ret = Vec::new();
2649                 let mut pending_events = self.pending_events.lock().unwrap();
2650                 mem::swap(&mut ret, &mut *pending_events);
2651                 ret
2652         }
2653 }
2654
2655 impl ChainListener for ChannelManager {
2656         fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
2657                 let header_hash = header.bitcoin_hash();
2658                 log_trace!(self, "Block {} at height {} connected with {} txn matched", header_hash, height, txn_matched.len());
2659                 let _ = self.total_consistency_lock.read().unwrap();
2660                 let mut failed_channels = Vec::new();
2661                 {
2662                         let mut channel_lock = self.channel_state.lock().unwrap();
2663                         let channel_state = channel_lock.borrow_parts();
2664                         let short_to_id = channel_state.short_to_id;
2665                         let pending_msg_events = channel_state.pending_msg_events;
2666                         channel_state.by_id.retain(|_, channel| {
2667                                 let chan_res = channel.block_connected(header, height, txn_matched, indexes_of_txn_matched);
2668                                 if let Ok(Some(funding_locked)) = chan_res {
2669                                         pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2670                                                 node_id: channel.get_their_node_id(),
2671                                                 msg: funding_locked,
2672                                         });
2673                                         if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
2674                                                 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2675                                                         node_id: channel.get_their_node_id(),
2676                                                         msg: announcement_sigs,
2677                                                 });
2678                                         }
2679                                         short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
2680                                 } else if let Err(e) = chan_res {
2681                                         pending_msg_events.push(events::MessageSendEvent::HandleError {
2682                                                 node_id: channel.get_their_node_id(),
2683                                                 action: Some(msgs::ErrorAction::SendErrorMessage { msg: e }),
2684                                         });
2685                                         return false;
2686                                 }
2687                                 if let Some(funding_txo) = channel.get_funding_txo() {
2688                                         for tx in txn_matched {
2689                                                 for inp in tx.input.iter() {
2690                                                         if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
2691                                                                 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()));
2692                                                                 if let Some(short_id) = channel.get_short_channel_id() {
2693                                                                         short_to_id.remove(&short_id);
2694                                                                 }
2695                                                                 // It looks like our counterparty went on-chain. We go ahead and
2696                                                                 // broadcast our latest local state as well here, just in case its
2697                                                                 // some kind of SPV attack, though we expect these to be dropped.
2698                                                                 failed_channels.push(channel.force_shutdown());
2699                                                                 if let Ok(update) = self.get_channel_update(&channel) {
2700                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2701                                                                                 msg: update
2702                                                                         });
2703                                                                 }
2704                                                                 return false;
2705                                                         }
2706                                                 }
2707                                         }
2708                                 }
2709                                 if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height) {
2710                                         if let Some(short_id) = channel.get_short_channel_id() {
2711                                                 short_to_id.remove(&short_id);
2712                                         }
2713                                         failed_channels.push(channel.force_shutdown());
2714                                         // If would_broadcast_at_height() is true, the channel_monitor will broadcast
2715                                         // the latest local tx for us, so we should skip that here (it doesn't really
2716                                         // hurt anything, but does make tests a bit simpler).
2717                                         failed_channels.last_mut().unwrap().0 = Vec::new();
2718                                         if let Ok(update) = self.get_channel_update(&channel) {
2719                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2720                                                         msg: update
2721                                                 });
2722                                         }
2723                                         return false;
2724                                 }
2725                                 true
2726                         });
2727                 }
2728                 for failure in failed_channels.drain(..) {
2729                         self.finish_force_close_channel(failure);
2730                 }
2731                 self.latest_block_height.store(height as usize, Ordering::Release);
2732                 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header_hash;
2733         }
2734
2735         /// We force-close the channel without letting our counterparty participate in the shutdown
2736         fn block_disconnected(&self, header: &BlockHeader) {
2737                 let _ = self.total_consistency_lock.read().unwrap();
2738                 let mut failed_channels = Vec::new();
2739                 {
2740                         let mut channel_lock = self.channel_state.lock().unwrap();
2741                         let channel_state = channel_lock.borrow_parts();
2742                         let short_to_id = channel_state.short_to_id;
2743                         let pending_msg_events = channel_state.pending_msg_events;
2744                         channel_state.by_id.retain(|_,  v| {
2745                                 if v.block_disconnected(header) {
2746                                         if let Some(short_id) = v.get_short_channel_id() {
2747                                                 short_to_id.remove(&short_id);
2748                                         }
2749                                         failed_channels.push(v.force_shutdown());
2750                                         if let Ok(update) = self.get_channel_update(&v) {
2751                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2752                                                         msg: update
2753                                                 });
2754                                         }
2755                                         false
2756                                 } else {
2757                                         true
2758                                 }
2759                         });
2760                 }
2761                 for failure in failed_channels.drain(..) {
2762                         self.finish_force_close_channel(failure);
2763                 }
2764                 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
2765                 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
2766         }
2767 }
2768
2769 impl ChannelMessageHandler for ChannelManager {
2770         //TODO: Handle errors and close channel (or so)
2771         fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), HandleError> {
2772                 let _ = self.total_consistency_lock.read().unwrap();
2773                 handle_error!(self, self.internal_open_channel(their_node_id, msg), their_node_id)
2774         }
2775
2776         fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), HandleError> {
2777                 let _ = self.total_consistency_lock.read().unwrap();
2778                 handle_error!(self, self.internal_accept_channel(their_node_id, msg), their_node_id)
2779         }
2780
2781         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), HandleError> {
2782                 let _ = self.total_consistency_lock.read().unwrap();
2783                 handle_error!(self, self.internal_funding_created(their_node_id, msg), their_node_id)
2784         }
2785
2786         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), HandleError> {
2787                 let _ = self.total_consistency_lock.read().unwrap();
2788                 handle_error!(self, self.internal_funding_signed(their_node_id, msg), their_node_id)
2789         }
2790
2791         fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), HandleError> {
2792                 let _ = self.total_consistency_lock.read().unwrap();
2793                 handle_error!(self, self.internal_funding_locked(their_node_id, msg), their_node_id)
2794         }
2795
2796         fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), HandleError> {
2797                 let _ = self.total_consistency_lock.read().unwrap();
2798                 handle_error!(self, self.internal_shutdown(their_node_id, msg), their_node_id)
2799         }
2800
2801         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), HandleError> {
2802                 let _ = self.total_consistency_lock.read().unwrap();
2803                 handle_error!(self, self.internal_closing_signed(their_node_id, msg), their_node_id)
2804         }
2805
2806         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), msgs::HandleError> {
2807                 let _ = self.total_consistency_lock.read().unwrap();
2808                 handle_error!(self, self.internal_update_add_htlc(their_node_id, msg), their_node_id)
2809         }
2810
2811         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), HandleError> {
2812                 let _ = self.total_consistency_lock.read().unwrap();
2813                 handle_error!(self, self.internal_update_fulfill_htlc(their_node_id, msg), their_node_id)
2814         }
2815
2816         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), HandleError> {
2817                 let _ = self.total_consistency_lock.read().unwrap();
2818                 handle_error!(self, self.internal_update_fail_htlc(their_node_id, msg), their_node_id)
2819         }
2820
2821         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), HandleError> {
2822                 let _ = self.total_consistency_lock.read().unwrap();
2823                 handle_error!(self, self.internal_update_fail_malformed_htlc(their_node_id, msg), their_node_id)
2824         }
2825
2826         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), HandleError> {
2827                 let _ = self.total_consistency_lock.read().unwrap();
2828                 handle_error!(self, self.internal_commitment_signed(their_node_id, msg), their_node_id)
2829         }
2830
2831         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), HandleError> {
2832                 let _ = self.total_consistency_lock.read().unwrap();
2833                 handle_error!(self, self.internal_revoke_and_ack(their_node_id, msg), their_node_id)
2834         }
2835
2836         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), HandleError> {
2837                 let _ = self.total_consistency_lock.read().unwrap();
2838                 handle_error!(self, self.internal_update_fee(their_node_id, msg), their_node_id)
2839         }
2840
2841         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), HandleError> {
2842                 let _ = self.total_consistency_lock.read().unwrap();
2843                 handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
2844         }
2845
2846         fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), HandleError> {
2847                 let _ = self.total_consistency_lock.read().unwrap();
2848                 handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), their_node_id)
2849         }
2850
2851         fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
2852                 let _ = self.total_consistency_lock.read().unwrap();
2853                 let mut failed_channels = Vec::new();
2854                 let mut failed_payments = Vec::new();
2855                 {
2856                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2857                         let channel_state = channel_state_lock.borrow_parts();
2858                         let short_to_id = channel_state.short_to_id;
2859                         let pending_msg_events = channel_state.pending_msg_events;
2860                         if no_connection_possible {
2861                                 log_debug!(self, "Failing all channels with {} due to no_connection_possible", log_pubkey!(their_node_id));
2862                                 channel_state.by_id.retain(|_, chan| {
2863                                         if chan.get_their_node_id() == *their_node_id {
2864                                                 if let Some(short_id) = chan.get_short_channel_id() {
2865                                                         short_to_id.remove(&short_id);
2866                                                 }
2867                                                 failed_channels.push(chan.force_shutdown());
2868                                                 if let Ok(update) = self.get_channel_update(&chan) {
2869                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2870                                                                 msg: update
2871                                                         });
2872                                                 }
2873                                                 false
2874                                         } else {
2875                                                 true
2876                                         }
2877                                 });
2878                         } else {
2879                                 log_debug!(self, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(their_node_id));
2880                                 channel_state.by_id.retain(|_, chan| {
2881                                         if chan.get_their_node_id() == *their_node_id {
2882                                                 //TODO: mark channel disabled (and maybe announce such after a timeout).
2883                                                 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused();
2884                                                 if !failed_adds.is_empty() {
2885                                                         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
2886                                                         failed_payments.push((chan_update, failed_adds));
2887                                                 }
2888                                                 if chan.is_shutdown() {
2889                                                         if let Some(short_id) = chan.get_short_channel_id() {
2890                                                                 short_to_id.remove(&short_id);
2891                                                         }
2892                                                         return false;
2893                                                 }
2894                                         }
2895                                         true
2896                                 })
2897                         }
2898                 }
2899                 for failure in failed_channels.drain(..) {
2900                         self.finish_force_close_channel(failure);
2901                 }
2902                 for (chan_update, mut htlc_sources) in failed_payments {
2903                         for (htlc_source, payment_hash) in htlc_sources.drain(..) {
2904                                 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
2905                         }
2906                 }
2907         }
2908
2909         fn peer_connected(&self, their_node_id: &PublicKey) {
2910                 log_debug!(self, "Generating channel_reestablish events for {}", log_pubkey!(their_node_id));
2911
2912                 let _ = self.total_consistency_lock.read().unwrap();
2913                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2914                 let channel_state = channel_state_lock.borrow_parts();
2915                 let pending_msg_events = channel_state.pending_msg_events;
2916                 channel_state.by_id.retain(|_, chan| {
2917                         if chan.get_their_node_id() == *their_node_id {
2918                                 if !chan.have_received_message() {
2919                                         // If we created this (outbound) channel while we were disconnected from the
2920                                         // peer we probably failed to send the open_channel message, which is now
2921                                         // lost. We can't have had anything pending related to this channel, so we just
2922                                         // drop it.
2923                                         false
2924                                 } else {
2925                                         pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
2926                                                 node_id: chan.get_their_node_id(),
2927                                                 msg: chan.get_channel_reestablish(),
2928                                         });
2929                                         true
2930                                 }
2931                         } else { true }
2932                 });
2933                 //TODO: Also re-broadcast announcement_signatures
2934         }
2935
2936         fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
2937                 let _ = self.total_consistency_lock.read().unwrap();
2938
2939                 if msg.channel_id == [0; 32] {
2940                         for chan in self.list_channels() {
2941                                 if chan.remote_network_id == *their_node_id {
2942                                         self.force_close_channel(&chan.channel_id);
2943                                 }
2944                         }
2945                 } else {
2946                         self.force_close_channel(&msg.channel_id);
2947                 }
2948         }
2949 }
2950
2951 const SERIALIZATION_VERSION: u8 = 1;
2952 const MIN_SERIALIZATION_VERSION: u8 = 1;
2953
2954 impl Writeable for PendingForwardHTLCInfo {
2955         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2956                 if let &Some(ref onion) = &self.onion_packet {
2957                         1u8.write(writer)?;
2958                         onion.write(writer)?;
2959                 } else {
2960                         0u8.write(writer)?;
2961                 }
2962                 self.incoming_shared_secret.write(writer)?;
2963                 self.payment_hash.write(writer)?;
2964                 self.short_channel_id.write(writer)?;
2965                 self.amt_to_forward.write(writer)?;
2966                 self.outgoing_cltv_value.write(writer)?;
2967                 Ok(())
2968         }
2969 }
2970
2971 impl<R: ::std::io::Read> Readable<R> for PendingForwardHTLCInfo {
2972         fn read(reader: &mut R) -> Result<PendingForwardHTLCInfo, DecodeError> {
2973                 let onion_packet = match <u8 as Readable<R>>::read(reader)? {
2974                         0 => None,
2975                         1 => Some(msgs::OnionPacket::read(reader)?),
2976                         _ => return Err(DecodeError::InvalidValue),
2977                 };
2978                 Ok(PendingForwardHTLCInfo {
2979                         onion_packet,
2980                         incoming_shared_secret: Readable::read(reader)?,
2981                         payment_hash: Readable::read(reader)?,
2982                         short_channel_id: Readable::read(reader)?,
2983                         amt_to_forward: Readable::read(reader)?,
2984                         outgoing_cltv_value: Readable::read(reader)?,
2985                 })
2986         }
2987 }
2988
2989 impl Writeable for HTLCFailureMsg {
2990         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2991                 match self {
2992                         &HTLCFailureMsg::Relay(ref fail_msg) => {
2993                                 0u8.write(writer)?;
2994                                 fail_msg.write(writer)?;
2995                         },
2996                         &HTLCFailureMsg::Malformed(ref fail_msg) => {
2997                                 1u8.write(writer)?;
2998                                 fail_msg.write(writer)?;
2999                         }
3000                 }
3001                 Ok(())
3002         }
3003 }
3004
3005 impl<R: ::std::io::Read> Readable<R> for HTLCFailureMsg {
3006         fn read(reader: &mut R) -> Result<HTLCFailureMsg, DecodeError> {
3007                 match <u8 as Readable<R>>::read(reader)? {
3008                         0 => Ok(HTLCFailureMsg::Relay(Readable::read(reader)?)),
3009                         1 => Ok(HTLCFailureMsg::Malformed(Readable::read(reader)?)),
3010                         _ => Err(DecodeError::InvalidValue),
3011                 }
3012         }
3013 }
3014
3015 impl Writeable for PendingHTLCStatus {
3016         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3017                 match self {
3018                         &PendingHTLCStatus::Forward(ref forward_info) => {
3019                                 0u8.write(writer)?;
3020                                 forward_info.write(writer)?;
3021                         },
3022                         &PendingHTLCStatus::Fail(ref fail_msg) => {
3023                                 1u8.write(writer)?;
3024                                 fail_msg.write(writer)?;
3025                         }
3026                 }
3027                 Ok(())
3028         }
3029 }
3030
3031 impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
3032         fn read(reader: &mut R) -> Result<PendingHTLCStatus, DecodeError> {
3033                 match <u8 as Readable<R>>::read(reader)? {
3034                         0 => Ok(PendingHTLCStatus::Forward(Readable::read(reader)?)),
3035                         1 => Ok(PendingHTLCStatus::Fail(Readable::read(reader)?)),
3036                         _ => Err(DecodeError::InvalidValue),
3037                 }
3038         }
3039 }
3040
3041 impl_writeable!(HTLCPreviousHopData, 0, {
3042         short_channel_id,
3043         htlc_id,
3044         incoming_packet_shared_secret
3045 });
3046
3047 impl Writeable for HTLCSource {
3048         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3049                 match self {
3050                         &HTLCSource::PreviousHopData(ref hop_data) => {
3051                                 0u8.write(writer)?;
3052                                 hop_data.write(writer)?;
3053                         },
3054                         &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } => {
3055                                 1u8.write(writer)?;
3056                                 route.write(writer)?;
3057                                 session_priv.write(writer)?;
3058                                 first_hop_htlc_msat.write(writer)?;
3059                         }
3060                 }
3061                 Ok(())
3062         }
3063 }
3064
3065 impl<R: ::std::io::Read> Readable<R> for HTLCSource {
3066         fn read(reader: &mut R) -> Result<HTLCSource, DecodeError> {
3067                 match <u8 as Readable<R>>::read(reader)? {
3068                         0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
3069                         1 => Ok(HTLCSource::OutboundRoute {
3070                                 route: Readable::read(reader)?,
3071                                 session_priv: Readable::read(reader)?,
3072                                 first_hop_htlc_msat: Readable::read(reader)?,
3073                         }),
3074                         _ => Err(DecodeError::InvalidValue),
3075                 }
3076         }
3077 }
3078
3079 impl Writeable for HTLCFailReason {
3080         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3081                 match self {
3082                         &HTLCFailReason::ErrorPacket { ref err } => {
3083                                 0u8.write(writer)?;
3084                                 err.write(writer)?;
3085                         },
3086                         &HTLCFailReason::Reason { ref failure_code, ref data } => {
3087                                 1u8.write(writer)?;
3088                                 failure_code.write(writer)?;
3089                                 data.write(writer)?;
3090                         }
3091                 }
3092                 Ok(())
3093         }
3094 }
3095
3096 impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
3097         fn read(reader: &mut R) -> Result<HTLCFailReason, DecodeError> {
3098                 match <u8 as Readable<R>>::read(reader)? {
3099                         0 => Ok(HTLCFailReason::ErrorPacket { err: Readable::read(reader)? }),
3100                         1 => Ok(HTLCFailReason::Reason {
3101                                 failure_code: Readable::read(reader)?,
3102                                 data: Readable::read(reader)?,
3103                         }),
3104                         _ => Err(DecodeError::InvalidValue),
3105                 }
3106         }
3107 }
3108
3109 impl_writeable!(HTLCForwardInfo, 0, {
3110         prev_short_channel_id,
3111         prev_htlc_id,
3112         forward_info
3113 });
3114
3115 impl Writeable for ChannelManager {
3116         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3117                 let _ = self.total_consistency_lock.write().unwrap();
3118
3119                 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
3120                 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
3121
3122                 self.genesis_hash.write(writer)?;
3123                 (self.latest_block_height.load(Ordering::Acquire) as u32).write(writer)?;
3124                 self.last_block_hash.lock().unwrap().write(writer)?;
3125
3126                 let channel_state = self.channel_state.lock().unwrap();
3127                 let mut unfunded_channels = 0;
3128                 for (_, channel) in channel_state.by_id.iter() {
3129                         if !channel.is_funding_initiated() {
3130                                 unfunded_channels += 1;
3131                         }
3132                 }
3133                 ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
3134                 for (_, channel) in channel_state.by_id.iter() {
3135                         if channel.is_funding_initiated() {
3136                                 channel.write(writer)?;
3137                         }
3138                 }
3139
3140                 (channel_state.forward_htlcs.len() as u64).write(writer)?;
3141                 for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
3142                         short_channel_id.write(writer)?;
3143                         (pending_forwards.len() as u64).write(writer)?;
3144                         for forward in pending_forwards {
3145                                 forward.write(writer)?;
3146                         }
3147                 }
3148
3149                 (channel_state.claimable_htlcs.len() as u64).write(writer)?;
3150                 for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
3151                         payment_hash.write(writer)?;
3152                         (previous_hops.len() as u64).write(writer)?;
3153                         for previous_hop in previous_hops {
3154                                 previous_hop.write(writer)?;
3155                         }
3156                 }
3157
3158                 Ok(())
3159         }
3160 }
3161
3162 /// Arguments for the creation of a ChannelManager that are not deserialized.
3163 ///
3164 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
3165 /// is:
3166 /// 1) Deserialize all stored ChannelMonitors.
3167 /// 2) Deserialize the ChannelManager by filling in this struct and calling <(Sha256dHash,
3168 ///    ChannelManager)>::read(reader, args).
3169 ///    This may result in closing some Channels if the ChannelMonitor is newer than the stored
3170 ///    ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
3171 /// 3) Register all relevant ChannelMonitor outpoints with your chain watch mechanism using
3172 ///    ChannelMonitor::get_monitored_outpoints and ChannelMonitor::get_funding_txo().
3173 /// 4) Reconnect blocks on your ChannelMonitors.
3174 /// 5) Move the ChannelMonitors into your local ManyChannelMonitor.
3175 /// 6) Disconnect/connect blocks on the ChannelManager.
3176 /// 7) Register the new ChannelManager with your ChainWatchInterface (this does not happen
3177 ///    automatically as it does in ChannelManager::new()).
3178 pub struct ChannelManagerReadArgs<'a> {
3179         /// The keys provider which will give us relevant keys. Some keys will be loaded during
3180         /// deserialization.
3181         pub keys_manager: Arc<KeysInterface>,
3182
3183         /// The fee_estimator for use in the ChannelManager in the future.
3184         ///
3185         /// No calls to the FeeEstimator will be made during deserialization.
3186         pub fee_estimator: Arc<FeeEstimator>,
3187         /// The ManyChannelMonitor for use in the ChannelManager in the future.
3188         ///
3189         /// No calls to the ManyChannelMonitor will be made during deserialization. It is assumed that
3190         /// you have deserialized ChannelMonitors separately and will add them to your
3191         /// ManyChannelMonitor after deserializing this ChannelManager.
3192         pub monitor: Arc<ManyChannelMonitor>,
3193         /// The ChainWatchInterface for use in the ChannelManager in the future.
3194         ///
3195         /// No calls to the ChainWatchInterface will be made during deserialization.
3196         pub chain_monitor: Arc<ChainWatchInterface>,
3197         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
3198         /// used to broadcast the latest local commitment transactions of channels which must be
3199         /// force-closed during deserialization.
3200         pub tx_broadcaster: Arc<BroadcasterInterface>,
3201         /// The Logger for use in the ChannelManager and which may be used to log information during
3202         /// deserialization.
3203         pub logger: Arc<Logger>,
3204         /// Default settings used for new channels. Any existing channels will continue to use the
3205         /// runtime settings which were stored when the ChannelManager was serialized.
3206         pub default_config: UserConfig,
3207
3208         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
3209         /// value.get_funding_txo() should be the key).
3210         ///
3211         /// If a monitor is inconsistent with the channel state during deserialization the channel will
3212         /// be force-closed using the data in the channelmonitor and the Channel will be dropped. This
3213         /// is true for missing channels as well. If there is a monitor missing for which we find
3214         /// channel data Err(DecodeError::InvalidValue) will be returned.
3215         ///
3216         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
3217         /// this struct.
3218         pub channel_monitors: &'a HashMap<OutPoint, &'a ChannelMonitor>,
3219 }
3220
3221 impl<'a, R : ::std::io::Read> ReadableArgs<R, ChannelManagerReadArgs<'a>> for (Sha256dHash, ChannelManager) {
3222         fn read(reader: &mut R, args: ChannelManagerReadArgs<'a>) -> Result<Self, DecodeError> {
3223                 let _ver: u8 = Readable::read(reader)?;
3224                 let min_ver: u8 = Readable::read(reader)?;
3225                 if min_ver > SERIALIZATION_VERSION {
3226                         return Err(DecodeError::UnknownVersion);
3227                 }
3228
3229                 let genesis_hash: Sha256dHash = Readable::read(reader)?;
3230                 let latest_block_height: u32 = Readable::read(reader)?;
3231                 let last_block_hash: Sha256dHash = Readable::read(reader)?;
3232
3233                 let mut closed_channels = Vec::new();
3234
3235                 let channel_count: u64 = Readable::read(reader)?;
3236                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
3237                 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3238                 let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3239                 for _ in 0..channel_count {
3240                         let mut channel: Channel = ReadableArgs::read(reader, args.logger.clone())?;
3241                         if channel.last_block_connected != last_block_hash {
3242                                 return Err(DecodeError::InvalidValue);
3243                         }
3244
3245                         let funding_txo = channel.channel_monitor().get_funding_txo().ok_or(DecodeError::InvalidValue)?;
3246                         funding_txo_set.insert(funding_txo.clone());
3247                         if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
3248                                 if channel.get_cur_local_commitment_transaction_number() != monitor.get_cur_local_commitment_number() ||
3249                                                 channel.get_revoked_remote_commitment_transaction_number() != monitor.get_min_seen_secret() ||
3250                                                 channel.get_cur_remote_commitment_transaction_number() != monitor.get_cur_remote_commitment_number() {
3251                                         let mut force_close_res = channel.force_shutdown();
3252                                         force_close_res.0 = monitor.get_latest_local_commitment_txn();
3253                                         closed_channels.push(force_close_res);
3254                                 } else {
3255                                         if let Some(short_channel_id) = channel.get_short_channel_id() {
3256                                                 short_to_id.insert(short_channel_id, channel.channel_id());
3257                                         }
3258                                         by_id.insert(channel.channel_id(), channel);
3259                                 }
3260                         } else {
3261                                 return Err(DecodeError::InvalidValue);
3262                         }
3263                 }
3264
3265                 for (ref funding_txo, ref monitor) in args.channel_monitors.iter() {
3266                         if !funding_txo_set.contains(funding_txo) {
3267                                 closed_channels.push((monitor.get_latest_local_commitment_txn(), Vec::new()));
3268                         }
3269                 }
3270
3271                 let forward_htlcs_count: u64 = Readable::read(reader)?;
3272                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
3273                 for _ in 0..forward_htlcs_count {
3274                         let short_channel_id = Readable::read(reader)?;
3275                         let pending_forwards_count: u64 = Readable::read(reader)?;
3276                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, 128));
3277                         for _ in 0..pending_forwards_count {
3278                                 pending_forwards.push(Readable::read(reader)?);
3279                         }
3280                         forward_htlcs.insert(short_channel_id, pending_forwards);
3281                 }
3282
3283                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
3284                 let mut claimable_htlcs = HashMap::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
3285                 for _ in 0..claimable_htlcs_count {
3286                         let payment_hash = Readable::read(reader)?;
3287                         let previous_hops_len: u64 = Readable::read(reader)?;
3288                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, 2));
3289                         for _ in 0..previous_hops_len {
3290                                 previous_hops.push(Readable::read(reader)?);
3291                         }
3292                         claimable_htlcs.insert(payment_hash, previous_hops);
3293                 }
3294
3295                 let channel_manager = ChannelManager {
3296                         genesis_hash,
3297                         fee_estimator: args.fee_estimator,
3298                         monitor: args.monitor,
3299                         chain_monitor: args.chain_monitor,
3300                         tx_broadcaster: args.tx_broadcaster,
3301
3302                         latest_block_height: AtomicUsize::new(latest_block_height as usize),
3303                         last_block_hash: Mutex::new(last_block_hash),
3304                         secp_ctx: Secp256k1::new(),
3305
3306                         channel_state: Mutex::new(ChannelHolder {
3307                                 by_id,
3308                                 short_to_id,
3309                                 next_forward: Instant::now(),
3310                                 forward_htlcs,
3311                                 claimable_htlcs,
3312                                 pending_msg_events: Vec::new(),
3313                         }),
3314                         our_network_key: args.keys_manager.get_node_secret(),
3315
3316                         pending_events: Mutex::new(Vec::new()),
3317                         total_consistency_lock: RwLock::new(()),
3318                         keys_manager: args.keys_manager,
3319                         logger: args.logger,
3320                         default_configuration: args.default_config,
3321                 };
3322
3323                 for close_res in closed_channels.drain(..) {
3324                         channel_manager.finish_force_close_channel(close_res);
3325                         //TODO: Broadcast channel update for closed channels, but only after we've made a
3326                         //connection or two.
3327                 }
3328
3329                 Ok((last_block_hash.clone(), channel_manager))
3330         }
3331 }
3332
3333 #[cfg(test)]
3334 mod tests {
3335         use chain::chaininterface;
3336         use chain::transaction::OutPoint;
3337         use chain::chaininterface::{ChainListener, ChainWatchInterface};
3338         use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor};
3339         use chain::keysinterface;
3340         use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
3341         use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,OnionKeys,RAACommitmentOrder, PaymentPreimage, PaymentHash};
3342         use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, ManyChannelMonitor};
3343         use ln::channel::{ACCEPTED_HTLC_SCRIPT_WEIGHT, OFFERED_HTLC_SCRIPT_WEIGHT};
3344         use ln::router::{Route, RouteHop, Router};
3345         use ln::msgs;
3346         use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate};
3347         use util::test_utils;
3348         use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
3349         use util::errors::APIError;
3350         use util::logger::Logger;
3351         use util::ser::{Writeable, Writer, ReadableArgs};
3352         use util::config::UserConfig;
3353
3354         use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
3355         use bitcoin::util::bip143;
3356         use bitcoin::util::address::Address;
3357         use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
3358         use bitcoin::blockdata::block::{Block, BlockHeader};
3359         use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType};
3360         use bitcoin::blockdata::script::{Builder, Script};
3361         use bitcoin::blockdata::opcodes;
3362         use bitcoin::blockdata::constants::genesis_block;
3363         use bitcoin::network::constants::Network;
3364
3365         use bitcoin_hashes::sha256::Hash as Sha256;
3366         use bitcoin_hashes::Hash;
3367
3368         use hex;
3369
3370         use secp256k1::{Secp256k1, Message};
3371         use secp256k1::key::{PublicKey,SecretKey};
3372
3373         use rand::{thread_rng,Rng};
3374
3375         use std::cell::RefCell;
3376         use std::collections::{BTreeSet, HashMap, HashSet};
3377         use std::default::Default;
3378         use std::rc::Rc;
3379         use std::sync::{Arc, Mutex};
3380         use std::sync::atomic::Ordering;
3381         use std::time::Instant;
3382         use std::mem;
3383
3384         fn build_test_onion_keys() -> Vec<OnionKeys> {
3385                 // Keys from BOLT 4, used in both test vector tests
3386                 let secp_ctx = Secp256k1::new();
3387
3388                 let route = Route {
3389                         hops: vec!(
3390                                         RouteHop {
3391                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
3392                                                 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
3393                                         },
3394                                         RouteHop {
3395                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
3396                                                 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
3397                                         },
3398                                         RouteHop {
3399                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
3400                                                 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
3401                                         },
3402                                         RouteHop {
3403                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..]).unwrap(),
3404                                                 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
3405                                         },
3406                                         RouteHop {
3407                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145").unwrap()[..]).unwrap(),
3408                                                 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
3409                                         },
3410                         ),
3411                 };
3412
3413                 let session_priv = SecretKey::from_slice(&secp_ctx, &hex::decode("4141414141414141414141414141414141414141414141414141414141414141").unwrap()[..]).unwrap();
3414
3415                 let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
3416                 assert_eq!(onion_keys.len(), route.hops.len());
3417                 onion_keys
3418         }
3419
3420         #[test]
3421         fn onion_vectors() {
3422                 // Packet creation test vectors from BOLT 4
3423                 let onion_keys = build_test_onion_keys();
3424
3425                 assert_eq!(onion_keys[0].shared_secret[..], hex::decode("53eb63ea8a3fec3b3cd433b85cd62a4b145e1dda09391b348c4e1cd36a03ea66").unwrap()[..]);
3426                 assert_eq!(onion_keys[0].blinding_factor[..], hex::decode("2ec2e5da605776054187180343287683aa6a51b4b1c04d6dd49c45d8cffb3c36").unwrap()[..]);
3427                 assert_eq!(onion_keys[0].ephemeral_pubkey.serialize()[..], hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]);
3428                 assert_eq!(onion_keys[0].rho, hex::decode("ce496ec94def95aadd4bec15cdb41a740c9f2b62347c4917325fcc6fb0453986").unwrap()[..]);
3429                 assert_eq!(onion_keys[0].mu, hex::decode("b57061dc6d0a2b9f261ac410c8b26d64ac5506cbba30267a649c28c179400eba").unwrap()[..]);
3430
3431                 assert_eq!(onion_keys[1].shared_secret[..], hex::decode("a6519e98832a0b179f62123b3567c106db99ee37bef036e783263602f3488fae").unwrap()[..]);
3432                 assert_eq!(onion_keys[1].blinding_factor[..], hex::decode("bf66c28bc22e598cfd574a1931a2bafbca09163df2261e6d0056b2610dab938f").unwrap()[..]);
3433                 assert_eq!(onion_keys[1].ephemeral_pubkey.serialize()[..], hex::decode("028f9438bfbf7feac2e108d677e3a82da596be706cc1cf342b75c7b7e22bf4e6e2").unwrap()[..]);
3434                 assert_eq!(onion_keys[1].rho, hex::decode("450ffcabc6449094918ebe13d4f03e433d20a3d28a768203337bc40b6e4b2c59").unwrap()[..]);
3435                 assert_eq!(onion_keys[1].mu, hex::decode("05ed2b4a3fb023c2ff5dd6ed4b9b6ea7383f5cfe9d59c11d121ec2c81ca2eea9").unwrap()[..]);
3436
3437                 assert_eq!(onion_keys[2].shared_secret[..], hex::decode("3a6b412548762f0dbccce5c7ae7bb8147d1caf9b5471c34120b30bc9c04891cc").unwrap()[..]);
3438                 assert_eq!(onion_keys[2].blinding_factor[..], hex::decode("a1f2dadd184eb1627049673f18c6325814384facdee5bfd935d9cb031a1698a5").unwrap()[..]);
3439                 assert_eq!(onion_keys[2].ephemeral_pubkey.serialize()[..], hex::decode("03bfd8225241ea71cd0843db7709f4c222f62ff2d4516fd38b39914ab6b83e0da0").unwrap()[..]);
3440                 assert_eq!(onion_keys[2].rho, hex::decode("11bf5c4f960239cb37833936aa3d02cea82c0f39fd35f566109c41f9eac8deea").unwrap()[..]);
3441                 assert_eq!(onion_keys[2].mu, hex::decode("caafe2820fa00eb2eeb78695ae452eba38f5a53ed6d53518c5c6edf76f3f5b78").unwrap()[..]);
3442
3443                 assert_eq!(onion_keys[3].shared_secret[..], hex::decode("21e13c2d7cfe7e18836df50872466117a295783ab8aab0e7ecc8c725503ad02d").unwrap()[..]);
3444                 assert_eq!(onion_keys[3].blinding_factor[..], hex::decode("7cfe0b699f35525029ae0fa437c69d0f20f7ed4e3916133f9cacbb13c82ff262").unwrap()[..]);
3445                 assert_eq!(onion_keys[3].ephemeral_pubkey.serialize()[..], hex::decode("031dde6926381289671300239ea8e57ffaf9bebd05b9a5b95beaf07af05cd43595").unwrap()[..]);
3446                 assert_eq!(onion_keys[3].rho, hex::decode("cbe784ab745c13ff5cffc2fbe3e84424aa0fd669b8ead4ee562901a4a4e89e9e").unwrap()[..]);
3447                 assert_eq!(onion_keys[3].mu, hex::decode("5052aa1b3d9f0655a0932e50d42f0c9ba0705142c25d225515c45f47c0036ee9").unwrap()[..]);
3448
3449                 assert_eq!(onion_keys[4].shared_secret[..], hex::decode("b5756b9b542727dbafc6765a49488b023a725d631af688fc031217e90770c328").unwrap()[..]);
3450                 assert_eq!(onion_keys[4].blinding_factor[..], hex::decode("c96e00dddaf57e7edcd4fb5954be5b65b09f17cb6d20651b4e90315be5779205").unwrap()[..]);
3451                 assert_eq!(onion_keys[4].ephemeral_pubkey.serialize()[..], hex::decode("03a214ebd875aab6ddfd77f22c5e7311d7f77f17a169e599f157bbcdae8bf071f4").unwrap()[..]);
3452                 assert_eq!(onion_keys[4].rho, hex::decode("034e18b8cc718e8af6339106e706c52d8df89e2b1f7e9142d996acf88df8799b").unwrap()[..]);
3453                 assert_eq!(onion_keys[4].mu, hex::decode("8e45e5c61c2b24cb6382444db6698727afb063adecd72aada233d4bf273d975a").unwrap()[..]);
3454
3455                 // Test vectors below are flat-out wrong: they claim to set outgoing_cltv_value to non-0 :/
3456                 let payloads = vec!(
3457                         msgs::OnionHopData {
3458                                 realm: 0,
3459                                 data: msgs::OnionRealm0HopData {
3460                                         short_channel_id: 0,
3461                                         amt_to_forward: 0,
3462                                         outgoing_cltv_value: 0,
3463                                 },
3464                                 hmac: [0; 32],
3465                         },
3466                         msgs::OnionHopData {
3467                                 realm: 0,
3468                                 data: msgs::OnionRealm0HopData {
3469                                         short_channel_id: 0x0101010101010101,
3470                                         amt_to_forward: 0x0100000001,
3471                                         outgoing_cltv_value: 0,
3472                                 },
3473                                 hmac: [0; 32],
3474                         },
3475                         msgs::OnionHopData {
3476                                 realm: 0,
3477                                 data: msgs::OnionRealm0HopData {
3478                                         short_channel_id: 0x0202020202020202,
3479                                         amt_to_forward: 0x0200000002,
3480                                         outgoing_cltv_value: 0,
3481                                 },
3482                                 hmac: [0; 32],
3483                         },
3484                         msgs::OnionHopData {
3485                                 realm: 0,
3486                                 data: msgs::OnionRealm0HopData {
3487                                         short_channel_id: 0x0303030303030303,
3488                                         amt_to_forward: 0x0300000003,
3489                                         outgoing_cltv_value: 0,
3490                                 },
3491                                 hmac: [0; 32],
3492                         },
3493                         msgs::OnionHopData {
3494                                 realm: 0,
3495                                 data: msgs::OnionRealm0HopData {
3496                                         short_channel_id: 0x0404040404040404,
3497                                         amt_to_forward: 0x0400000004,
3498                                         outgoing_cltv_value: 0,
3499                                 },
3500                                 hmac: [0; 32],
3501                         },
3502                 );
3503
3504                 let packet = ChannelManager::construct_onion_packet(payloads, onion_keys, &PaymentHash([0x42; 32]));
3505                 // Just check the final packet encoding, as it includes all the per-hop vectors in it
3506                 // anyway...
3507                 assert_eq!(packet.encode(), hex::decode("0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619e5f14350c2a76fc232b5e46d421e9615471ab9e0bc887beff8c95fdb878f7b3a716a996c7845c93d90e4ecbb9bde4ece2f69425c99e4bc820e44485455f135edc0d10f7d61ab590531cf08000179a333a347f8b4072f216400406bdf3bf038659793d4a1fd7b246979e3150a0a4cb052c9ec69acf0f48c3d39cd55675fe717cb7d80ce721caad69320c3a469a202f1e468c67eaf7a7cd8226d0fd32f7b48084dca885d56047694762b67021713ca673929c163ec36e04e40ca8e1c6d17569419d3039d9a1ec866abe044a9ad635778b961fc0776dc832b3a451bd5d35072d2269cf9b040f6b7a7dad84fb114ed413b1426cb96ceaf83825665ed5a1d002c1687f92465b49ed4c7f0218ff8c6c7dd7221d589c65b3b9aaa71a41484b122846c7c7b57e02e679ea8469b70e14fe4f70fee4d87b910cf144be6fe48eef24da475c0b0bcc6565ae82cd3f4e3b24c76eaa5616c6111343306ab35c1fe5ca4a77c0e314ed7dba39d6f1e0de791719c241a939cc493bea2bae1c1e932679ea94d29084278513c77b899cc98059d06a27d171b0dbdf6bee13ddc4fc17a0c4d2827d488436b57baa167544138ca2e64a11b43ac8a06cd0c2fba2d4d900ed2d9205305e2d7383cc98dacb078133de5f6fb6bed2ef26ba92cea28aafc3b9948dd9ae5559e8bd6920b8cea462aa445ca6a95e0e7ba52961b181c79e73bd581821df2b10173727a810c92b83b5ba4a0403eb710d2ca10689a35bec6c3a708e9e92f7d78ff3c5d9989574b00c6736f84c199256e76e19e78f0c98a9d580b4a658c84fc8f2096c2fbea8f5f8c59d0fdacb3be2802ef802abbecb3aba4acaac69a0e965abd8981e9896b1f6ef9d60f7a164b371af869fd0e48073742825e9434fc54da837e120266d53302954843538ea7c6c3dbfb4ff3b2fdbe244437f2a153ccf7bdb4c92aa08102d4f3cff2ae5ef86fab4653595e6a5837fa2f3e29f27a9cde5966843fb847a4a61f1e76c281fe8bb2b0a181d096100db5a1a5ce7a910238251a43ca556712eaadea167fb4d7d75825e440f3ecd782036d7574df8bceacb397abefc5f5254d2722215c53ff54af8299aaaad642c6d72a14d27882d9bbd539e1cc7a527526ba89b8c037ad09120e98ab042d3e8652b31ae0e478516bfaf88efca9f3676ffe99d2819dcaeb7610a626695f53117665d267d3f7abebd6bbd6733f645c72c389f03855bdf1e4b8075b516569b118233a0f0971d24b83113c0b096f5216a207ca99a7cddc81c130923fe3d91e7508c9ac5f2e914ff5dccab9e558566fa14efb34ac98d878580814b94b73acbfde9072f30b881f7f0fff42d4045d1ace6322d86a97d164aa84d93a60498065cc7c20e636f5862dc81531a88c60305a2e59a985be327a6902e4bed986dbf4a0b50c217af0ea7fdf9ab37f9ea1a1aaa72f54cf40154ea9b269f1a7c09f9f43245109431a175d50e2db0132337baa0ef97eed0fcf20489da36b79a1172faccc2f7ded7c60e00694282d93359c4682135642bc81f433574aa8ef0c97b4ade7ca372c5ffc23c7eddd839bab4e0f14d6df15c9dbeab176bec8b5701cf054eb3072f6dadc98f88819042bf10c407516ee58bce33fbe3b3d86a54255e577db4598e30a135361528c101683a5fcde7e8ba53f3456254be8f45fe3a56120ae96ea3773631fcb3873aa3abd91bcff00bd38bd43697a2e789e00da6077482e7b1b1a677b5afae4c54e6cbdf7377b694eb7d7a5b913476a5be923322d3de06060fd5e819635232a2cf4f0731da13b8546d1d6d4f8d75b9fce6c2341a71b0ea6f780df54bfdb0dd5cd9855179f602f9172307c7268724c3618e6817abd793adc214a0dc0bc616816632f27ea336fb56dfd").unwrap());
3508         }
3509
3510         #[test]
3511         fn test_failure_packet_onion() {
3512                 // Returning Errors test vectors from BOLT 4
3513
3514                 let onion_keys = build_test_onion_keys();
3515                 let onion_error = ChannelManager::build_failure_packet(&onion_keys[4].shared_secret[..], 0x2002, &[0; 0]);
3516                 assert_eq!(onion_error.encode(), hex::decode("4c2fc8bc08510334b6833ad9c3e79cd1b52ae59dfe5c2a4b23ead50f09f7ee0b0002200200fe0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap());
3517
3518                 let onion_packet_1 = ChannelManager::encrypt_failure_packet(&onion_keys[4].shared_secret[..], &onion_error.encode()[..]);
3519                 assert_eq!(onion_packet_1.data, hex::decode("a5e6bd0c74cb347f10cce367f949098f2457d14c046fd8a22cb96efb30b0fdcda8cb9168b50f2fd45edd73c1b0c8b33002df376801ff58aaa94000bf8a86f92620f343baef38a580102395ae3abf9128d1047a0736ff9b83d456740ebbb4aeb3aa9737f18fb4afb4aa074fb26c4d702f42968888550a3bded8c05247e045b866baef0499f079fdaeef6538f31d44deafffdfd3afa2fb4ca9082b8f1c465371a9894dd8c243fb4847e004f5256b3e90e2edde4c9fb3082ddfe4d1e734cacd96ef0706bf63c9984e22dc98851bcccd1c3494351feb458c9c6af41c0044bea3c47552b1d992ae542b17a2d0bba1a096c78d169034ecb55b6e3a7263c26017f033031228833c1daefc0dedb8cf7c3e37c9c37ebfe42f3225c326e8bcfd338804c145b16e34e4").unwrap());
3520
3521                 let onion_packet_2 = ChannelManager::encrypt_failure_packet(&onion_keys[3].shared_secret[..], &onion_packet_1.data[..]);
3522                 assert_eq!(onion_packet_2.data, hex::decode("c49a1ce81680f78f5f2000cda36268de34a3f0a0662f55b4e837c83a8773c22aa081bab1616a0011585323930fa5b9fae0c85770a2279ff59ec427ad1bbff9001c0cd1497004bd2a0f68b50704cf6d6a4bf3c8b6a0833399a24b3456961ba00736785112594f65b6b2d44d9f5ea4e49b5e1ec2af978cbe31c67114440ac51a62081df0ed46d4a3df295da0b0fe25c0115019f03f15ec86fabb4c852f83449e812f141a9395b3f70b766ebbd4ec2fae2b6955bd8f32684c15abfe8fd3a6261e52650e8807a92158d9f1463261a925e4bfba44bd20b166d532f0017185c3a6ac7957adefe45559e3072c8dc35abeba835a8cb01a71a15c736911126f27d46a36168ca5ef7dccd4e2886212602b181463e0dd30185c96348f9743a02aca8ec27c0b90dca270").unwrap());
3523
3524                 let onion_packet_3 = ChannelManager::encrypt_failure_packet(&onion_keys[2].shared_secret[..], &onion_packet_2.data[..]);
3525                 assert_eq!(onion_packet_3.data, hex::decode("a5d3e8634cfe78b2307d87c6d90be6fe7855b4f2cc9b1dfb19e92e4b79103f61ff9ac25f412ddfb7466e74f81b3e545563cdd8f5524dae873de61d7bdfccd496af2584930d2b566b4f8d3881f8c043df92224f38cf094cfc09d92655989531524593ec6d6caec1863bdfaa79229b5020acc034cd6deeea1021c50586947b9b8e6faa83b81fbfa6133c0af5d6b07c017f7158fa94f0d206baf12dda6b68f785b773b360fd0497e16cc402d779c8d48d0fa6315536ef0660f3f4e1865f5b38ea49c7da4fd959de4e83ff3ab686f059a45c65ba2af4a6a79166aa0f496bf04d06987b6d2ea205bdb0d347718b9aeff5b61dfff344993a275b79717cd815b6ad4c0beb568c4ac9c36ff1c315ec1119a1993c4b61e6eaa0375e0aaf738ac691abd3263bf937e3").unwrap());
3526
3527                 let onion_packet_4 = ChannelManager::encrypt_failure_packet(&onion_keys[1].shared_secret[..], &onion_packet_3.data[..]);
3528                 assert_eq!(onion_packet_4.data, hex::decode("aac3200c4968f56b21f53e5e374e3a2383ad2b1b6501bbcc45abc31e59b26881b7dfadbb56ec8dae8857add94e6702fb4c3a4de22e2e669e1ed926b04447fc73034bb730f4932acd62727b75348a648a1128744657ca6a4e713b9b646c3ca66cac02cdab44dd3439890ef3aaf61708714f7375349b8da541b2548d452d84de7084bb95b3ac2345201d624d31f4d52078aa0fa05a88b4e20202bd2b86ac5b52919ea305a8949de95e935eed0319cf3cf19ebea61d76ba92532497fcdc9411d06bcd4275094d0a4a3c5d3a945e43305a5a9256e333e1f64dbca5fcd4e03a39b9012d197506e06f29339dfee3331995b21615337ae060233d39befea925cc262873e0530408e6990f1cbd233a150ef7b004ff6166c70c68d9f8c853c1abca640b8660db2921").unwrap());
3529
3530                 let onion_packet_5 = ChannelManager::encrypt_failure_packet(&onion_keys[0].shared_secret[..], &onion_packet_4.data[..]);
3531                 assert_eq!(onion_packet_5.data, hex::decode("9c5add3963fc7f6ed7f148623c84134b5647e1306419dbe2174e523fa9e2fbed3a06a19f899145610741c83ad40b7712aefaddec8c6baf7325d92ea4ca4d1df8bce517f7e54554608bf2bd8071a4f52a7a2f7ffbb1413edad81eeea5785aa9d990f2865dc23b4bc3c301a94eec4eabebca66be5cf638f693ec256aec514620cc28ee4a94bd9565bc4d4962b9d3641d4278fb319ed2b84de5b665f307a2db0f7fbb757366067d88c50f7e829138fde4f78d39b5b5802f1b92a8a820865af5cc79f9f30bc3f461c66af95d13e5e1f0381c184572a91dee1c849048a647a1158cf884064deddbf1b0b88dfe2f791428d0ba0f6fb2f04e14081f69165ae66d9297c118f0907705c9c4954a199bae0bb96fad763d690e7daa6cfda59ba7f2c8d11448b604d12d").unwrap());
3532         }
3533
3534         fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
3535                 assert!(chain.does_match_tx(tx));
3536                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3537                 chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
3538                 for i in 2..100 {
3539                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3540                         chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
3541                 }
3542         }
3543
3544         struct Node {
3545                 chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
3546                 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
3547                 chan_monitor: Arc<test_utils::TestChannelMonitor>,
3548                 keys_manager: Arc<test_utils::TestKeysInterface>,
3549                 node: Arc<ChannelManager>,
3550                 router: Router,
3551                 node_seed: [u8; 32],
3552                 network_payment_count: Rc<RefCell<u8>>,
3553                 network_chan_count: Rc<RefCell<u32>>,
3554         }
3555         impl Drop for Node {
3556                 fn drop(&mut self) {
3557                         if !::std::thread::panicking() {
3558                                 // Check that we processed all pending events
3559                                 assert_eq!(self.node.get_and_clear_pending_msg_events().len(), 0);
3560                                 assert_eq!(self.node.get_and_clear_pending_events().len(), 0);
3561                                 assert_eq!(self.chan_monitor.added_monitors.lock().unwrap().len(), 0);
3562                         }
3563                 }
3564         }
3565
3566         fn create_chan_between_nodes(node_a: &Node, node_b: &Node) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3567                 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001)
3568         }
3569
3570         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) {
3571                 let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat);
3572                 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
3573                 (announcement, as_update, bs_update, channel_id, tx)
3574         }
3575
3576         macro_rules! get_revoke_commit_msgs {
3577                 ($node: expr, $node_id: expr) => {
3578                         {
3579                                 let events = $node.node.get_and_clear_pending_msg_events();
3580                                 assert_eq!(events.len(), 2);
3581                                 (match events[0] {
3582                                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3583                                                 assert_eq!(*node_id, $node_id);
3584                                                 (*msg).clone()
3585                                         },
3586                                         _ => panic!("Unexpected event"),
3587                                 }, match events[1] {
3588                                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3589                                                 assert_eq!(*node_id, $node_id);
3590                                                 assert!(updates.update_add_htlcs.is_empty());
3591                                                 assert!(updates.update_fulfill_htlcs.is_empty());
3592                                                 assert!(updates.update_fail_htlcs.is_empty());
3593                                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
3594                                                 assert!(updates.update_fee.is_none());
3595                                                 updates.commitment_signed.clone()
3596                                         },
3597                                         _ => panic!("Unexpected event"),
3598                                 })
3599                         }
3600                 }
3601         }
3602
3603         macro_rules! get_event_msg {
3604                 ($node: expr, $event_type: path, $node_id: expr) => {
3605                         {
3606                                 let events = $node.node.get_and_clear_pending_msg_events();
3607                                 assert_eq!(events.len(), 1);
3608                                 match events[0] {
3609                                         $event_type { ref node_id, ref msg } => {
3610                                                 assert_eq!(*node_id, $node_id);
3611                                                 (*msg).clone()
3612                                         },
3613                                         _ => panic!("Unexpected event"),
3614                                 }
3615                         }
3616                 }
3617         }
3618
3619         macro_rules! get_htlc_update_msgs {
3620                 ($node: expr, $node_id: expr) => {
3621                         {
3622                                 let events = $node.node.get_and_clear_pending_msg_events();
3623                                 assert_eq!(events.len(), 1);
3624                                 match events[0] {
3625                                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3626                                                 assert_eq!(*node_id, $node_id);
3627                                                 (*updates).clone()
3628                                         },
3629                                         _ => panic!("Unexpected event"),
3630                                 }
3631                         }
3632                 }
3633         }
3634
3635         macro_rules! get_feerate {
3636                 ($node: expr, $channel_id: expr) => {
3637                         {
3638                                 let chan_lock = $node.node.channel_state.lock().unwrap();
3639                                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
3640                                 chan.get_feerate()
3641                         }
3642                 }
3643         }
3644
3645
3646         fn create_chan_between_nodes_with_value_init(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> Transaction {
3647                 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
3648                 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();
3649                 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();
3650
3651                 let chan_id = *node_a.network_chan_count.borrow();
3652                 let tx;
3653                 let funding_output;
3654
3655                 let events_2 = node_a.node.get_and_clear_pending_events();
3656                 assert_eq!(events_2.len(), 1);
3657                 match events_2[0] {
3658                         Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
3659                                 assert_eq!(*channel_value_satoshis, channel_value);
3660                                 assert_eq!(user_channel_id, 42);
3661
3662                                 tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
3663                                         value: *channel_value_satoshis, script_pubkey: output_script.clone(),
3664                                 }]};
3665                                 funding_output = OutPoint::new(tx.txid(), 0);
3666
3667                                 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
3668                                 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3669                                 assert_eq!(added_monitors.len(), 1);
3670                                 assert_eq!(added_monitors[0].0, funding_output);
3671                                 added_monitors.clear();
3672                         },
3673                         _ => panic!("Unexpected event"),
3674                 }
3675
3676                 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();
3677                 {
3678                         let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
3679                         assert_eq!(added_monitors.len(), 1);
3680                         assert_eq!(added_monitors[0].0, funding_output);
3681                         added_monitors.clear();
3682                 }
3683
3684                 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();
3685                 {
3686                         let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3687                         assert_eq!(added_monitors.len(), 1);
3688                         assert_eq!(added_monitors[0].0, funding_output);
3689                         added_monitors.clear();
3690                 }
3691
3692                 let events_4 = node_a.node.get_and_clear_pending_events();
3693                 assert_eq!(events_4.len(), 1);
3694                 match events_4[0] {
3695                         Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
3696                                 assert_eq!(user_channel_id, 42);
3697                                 assert_eq!(*funding_txo, funding_output);
3698                         },
3699                         _ => panic!("Unexpected event"),
3700                 };
3701
3702                 tx
3703         }
3704
3705         fn create_chan_between_nodes_with_value_confirm(node_a: &Node, node_b: &Node, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
3706                 confirm_transaction(&node_b.chain_monitor, &tx, tx.version);
3707                 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();
3708
3709                 let channel_id;
3710
3711                 confirm_transaction(&node_a.chain_monitor, &tx, tx.version);
3712                 let events_6 = node_a.node.get_and_clear_pending_msg_events();
3713                 assert_eq!(events_6.len(), 2);
3714                 ((match events_6[0] {
3715                         MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3716                                 channel_id = msg.channel_id.clone();
3717                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
3718                                 msg.clone()
3719                         },
3720                         _ => panic!("Unexpected event"),
3721                 }, match events_6[1] {
3722                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3723                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
3724                                 msg.clone()
3725                         },
3726                         _ => panic!("Unexpected event"),
3727                 }), channel_id)
3728         }
3729
3730         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) {
3731                 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat);
3732                 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
3733                 (msgs, chan_id, tx)
3734         }
3735
3736         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) {
3737                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0).unwrap();
3738                 let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
3739                 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1).unwrap();
3740
3741                 let events_7 = node_b.node.get_and_clear_pending_msg_events();
3742                 assert_eq!(events_7.len(), 1);
3743                 let (announcement, bs_update) = match events_7[0] {
3744                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3745                                 (msg, update_msg)
3746                         },
3747                         _ => panic!("Unexpected event"),
3748                 };
3749
3750                 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs).unwrap();
3751                 let events_8 = node_a.node.get_and_clear_pending_msg_events();
3752                 assert_eq!(events_8.len(), 1);
3753                 let as_update = match events_8[0] {
3754                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3755                                 assert!(*announcement == *msg);
3756                                 assert_eq!(update_msg.contents.short_channel_id, announcement.contents.short_channel_id);
3757                                 assert_eq!(update_msg.contents.short_channel_id, bs_update.contents.short_channel_id);
3758                                 update_msg
3759                         },
3760                         _ => panic!("Unexpected event"),
3761                 };
3762
3763                 *node_a.network_chan_count.borrow_mut() += 1;
3764
3765                 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
3766         }
3767
3768         fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3769                 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001)
3770         }
3771
3772         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) {
3773                 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat);
3774                 for node in nodes {
3775                         assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
3776                         node.router.handle_channel_update(&chan_announcement.1).unwrap();
3777                         node.router.handle_channel_update(&chan_announcement.2).unwrap();
3778                 }
3779                 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
3780         }
3781
3782         macro_rules! check_spends {
3783                 ($tx: expr, $spends_tx: expr) => {
3784                         {
3785                                 let mut funding_tx_map = HashMap::new();
3786                                 let spends_tx = $spends_tx;
3787                                 funding_tx_map.insert(spends_tx.txid(), spends_tx);
3788                                 $tx.verify(&funding_tx_map).unwrap();
3789                         }
3790                 }
3791         }
3792
3793         macro_rules! get_closing_signed_broadcast {
3794                 ($node: expr, $dest_pubkey: expr) => {
3795                         {
3796                                 let events = $node.get_and_clear_pending_msg_events();
3797                                 assert!(events.len() == 1 || events.len() == 2);
3798                                 (match events[events.len() - 1] {
3799                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
3800                                                 assert_eq!(msg.contents.flags & 2, 2);
3801                                                 msg.clone()
3802                                         },
3803                                         _ => panic!("Unexpected event"),
3804                                 }, if events.len() == 2 {
3805                                         match events[0] {
3806                                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3807                                                         assert_eq!(*node_id, $dest_pubkey);
3808                                                         Some(msg.clone())
3809                                                 },
3810                                                 _ => panic!("Unexpected event"),
3811                                         }
3812                                 } else { None })
3813                         }
3814                 }
3815         }
3816
3817         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) {
3818                 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) };
3819                 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
3820                 let (tx_a, tx_b);
3821
3822                 node_a.close_channel(channel_id).unwrap();
3823                 node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id())).unwrap();
3824
3825                 let events_1 = node_b.get_and_clear_pending_msg_events();
3826                 assert!(events_1.len() >= 1);
3827                 let shutdown_b = match events_1[0] {
3828                         MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
3829                                 assert_eq!(node_id, &node_a.get_our_node_id());
3830                                 msg.clone()
3831                         },
3832                         _ => panic!("Unexpected event"),
3833                 };
3834
3835                 let closing_signed_b = if !close_inbound_first {
3836                         assert_eq!(events_1.len(), 1);
3837                         None
3838                 } else {
3839                         Some(match events_1[1] {
3840                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3841                                         assert_eq!(node_id, &node_a.get_our_node_id());
3842                                         msg.clone()
3843                                 },
3844                                 _ => panic!("Unexpected event"),
3845                         })
3846                 };
3847
3848                 node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b).unwrap();
3849                 let (as_update, bs_update) = if close_inbound_first {
3850                         assert!(node_a.get_and_clear_pending_msg_events().is_empty());
3851                         node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3852                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3853                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3854                         let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3855
3856                         node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
3857                         let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3858                         assert!(none_b.is_none());
3859                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3860                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3861                         (as_update, bs_update)
3862                 } else {
3863                         let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
3864
3865                         node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a).unwrap();
3866                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3867                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3868                         let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3869
3870                         node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3871                         let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3872                         assert!(none_a.is_none());
3873                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3874                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3875                         (as_update, bs_update)
3876                 };
3877                 assert_eq!(tx_a, tx_b);
3878                 check_spends!(tx_a, funding_tx);
3879
3880                 (as_update, bs_update, tx_a)
3881         }
3882
3883         struct SendEvent {
3884                 node_id: PublicKey,
3885                 msgs: Vec<msgs::UpdateAddHTLC>,
3886                 commitment_msg: msgs::CommitmentSigned,
3887         }
3888         impl SendEvent {
3889                 fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
3890                         assert!(updates.update_fulfill_htlcs.is_empty());
3891                         assert!(updates.update_fail_htlcs.is_empty());
3892                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3893                         assert!(updates.update_fee.is_none());
3894                         SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
3895                 }
3896
3897                 fn from_event(event: MessageSendEvent) -> SendEvent {
3898                         match event {
3899                                 MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
3900                                 _ => panic!("Unexpected event type!"),
3901                         }
3902                 }
3903
3904                 fn from_node(node: &Node) -> SendEvent {
3905                         let mut events = node.node.get_and_clear_pending_msg_events();
3906                         assert_eq!(events.len(), 1);
3907                         SendEvent::from_event(events.pop().unwrap())
3908                 }
3909         }
3910
3911         macro_rules! check_added_monitors {
3912                 ($node: expr, $count: expr) => {
3913                         {
3914                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
3915                                 assert_eq!(added_monitors.len(), $count);
3916                                 added_monitors.clear();
3917                         }
3918                 }
3919         }
3920
3921         macro_rules! commitment_signed_dance {
3922                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
3923                         {
3924                                 check_added_monitors!($node_a, 0);
3925                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3926                                 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3927                                 check_added_monitors!($node_a, 1);
3928                                 commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
3929                         }
3930                 };
3931                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
3932                         {
3933                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
3934                                 check_added_monitors!($node_b, 0);
3935                                 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3936                                 $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
3937                                 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3938                                 check_added_monitors!($node_b, 1);
3939                                 $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed).unwrap();
3940                                 let (bs_revoke_and_ack, extra_msg_option) = {
3941                                         let events = $node_b.node.get_and_clear_pending_msg_events();
3942                                         assert!(events.len() <= 2);
3943                                         (match events[0] {
3944                                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3945                                                         assert_eq!(*node_id, $node_a.node.get_our_node_id());
3946                                                         (*msg).clone()
3947                                                 },
3948                                                 _ => panic!("Unexpected event"),
3949                                         }, events.get(1).map(|e| e.clone()))
3950                                 };
3951                                 check_added_monitors!($node_b, 1);
3952                                 if $fail_backwards {
3953                                         assert!($node_a.node.get_and_clear_pending_events().is_empty());
3954                                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3955                                 }
3956                                 (extra_msg_option, bs_revoke_and_ack)
3957                         }
3958                 };
3959                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
3960                         {
3961                                 check_added_monitors!($node_a, 0);
3962                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3963                                 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3964                                 check_added_monitors!($node_a, 1);
3965                                 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
3966                                 assert!(extra_msg_option.is_none());
3967                                 bs_revoke_and_ack
3968                         }
3969                 };
3970                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
3971                         {
3972                                 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
3973                                 $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
3974                                 {
3975                                         let mut added_monitors = $node_a.chan_monitor.added_monitors.lock().unwrap();
3976                                         if $fail_backwards {
3977                                                 assert_eq!(added_monitors.len(), 2);
3978                                                 assert!(added_monitors[0].0 != added_monitors[1].0);
3979                                         } else {
3980                                                 assert_eq!(added_monitors.len(), 1);
3981                                         }
3982                                         added_monitors.clear();
3983                                 }
3984                                 extra_msg_option
3985                         }
3986                 };
3987                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
3988                         {
3989                                 assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
3990                         }
3991                 };
3992                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
3993                         {
3994                                 commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
3995                                 if $fail_backwards {
3996                                         let channel_state = $node_a.node.channel_state.lock().unwrap();
3997                                         assert_eq!(channel_state.pending_msg_events.len(), 1);
3998                                         if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
3999                                                 assert_ne!(*node_id, $node_b.node.get_our_node_id());
4000                                         } else { panic!("Unexpected event"); }
4001                                 } else {
4002                                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
4003                                 }
4004                         }
4005                 }
4006         }
4007
4008         macro_rules! get_payment_preimage_hash {
4009                 ($node: expr) => {
4010                         {
4011                                 let payment_preimage = PaymentPreimage([*$node.network_payment_count.borrow(); 32]);
4012                                 *$node.network_payment_count.borrow_mut() += 1;
4013                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
4014                                 (payment_preimage, payment_hash)
4015                         }
4016                 }
4017         }
4018
4019         fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
4020                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4021
4022                 let mut payment_event = {
4023                         origin_node.node.send_payment(route, our_payment_hash).unwrap();
4024                         check_added_monitors!(origin_node, 1);
4025
4026                         let mut events = origin_node.node.get_and_clear_pending_msg_events();
4027                         assert_eq!(events.len(), 1);
4028                         SendEvent::from_event(events.remove(0))
4029                 };
4030                 let mut prev_node = origin_node;
4031
4032                 for (idx, &node) in expected_route.iter().enumerate() {
4033                         assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
4034
4035                         node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4036                         check_added_monitors!(node, 0);
4037                         commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
4038
4039                         let events_1 = node.node.get_and_clear_pending_events();
4040                         assert_eq!(events_1.len(), 1);
4041                         match events_1[0] {
4042                                 Event::PendingHTLCsForwardable { .. } => { },
4043                                 _ => panic!("Unexpected event"),
4044                         };
4045
4046                         node.node.channel_state.lock().unwrap().next_forward = Instant::now();
4047                         node.node.process_pending_htlc_forwards();
4048
4049                         if idx == expected_route.len() - 1 {
4050                                 let events_2 = node.node.get_and_clear_pending_events();
4051                                 assert_eq!(events_2.len(), 1);
4052                                 match events_2[0] {
4053                                         Event::PaymentReceived { ref payment_hash, amt } => {
4054                                                 assert_eq!(our_payment_hash, *payment_hash);
4055                                                 assert_eq!(amt, recv_value);
4056                                         },
4057                                         _ => panic!("Unexpected event"),
4058                                 }
4059                         } else {
4060                                 let mut events_2 = node.node.get_and_clear_pending_msg_events();
4061                                 assert_eq!(events_2.len(), 1);
4062                                 check_added_monitors!(node, 1);
4063                                 payment_event = SendEvent::from_event(events_2.remove(0));
4064                                 assert_eq!(payment_event.msgs.len(), 1);
4065                         }
4066
4067                         prev_node = node;
4068                 }
4069
4070                 (our_payment_preimage, our_payment_hash)
4071         }
4072
4073         fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: PaymentPreimage) {
4074                 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
4075                 check_added_monitors!(expected_route.last().unwrap(), 1);
4076
4077                 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
4078                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4079                 macro_rules! get_next_msgs {
4080                         ($node: expr) => {
4081                                 {
4082                                         let events = $node.node.get_and_clear_pending_msg_events();
4083                                         assert_eq!(events.len(), 1);
4084                                         match events[0] {
4085                                                 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 } } => {
4086                                                         assert!(update_add_htlcs.is_empty());
4087                                                         assert_eq!(update_fulfill_htlcs.len(), 1);
4088                                                         assert!(update_fail_htlcs.is_empty());
4089                                                         assert!(update_fail_malformed_htlcs.is_empty());
4090                                                         assert!(update_fee.is_none());
4091                                                         expected_next_node = node_id.clone();
4092                                                         Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()))
4093                                                 },
4094                                                 _ => panic!("Unexpected event"),
4095                                         }
4096                                 }
4097                         }
4098                 }
4099
4100                 macro_rules! last_update_fulfill_dance {
4101                         ($node: expr, $prev_node: expr) => {
4102                                 {
4103                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4104                                         check_added_monitors!($node, 0);
4105                                         assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4106                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4107                                 }
4108                         }
4109                 }
4110                 macro_rules! mid_update_fulfill_dance {
4111                         ($node: expr, $prev_node: expr, $new_msgs: expr) => {
4112                                 {
4113                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4114                                         check_added_monitors!($node, 1);
4115                                         let new_next_msgs = if $new_msgs {
4116                                                 get_next_msgs!($node)
4117                                         } else {
4118                                                 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4119                                                 None
4120                                         };
4121                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4122                                         next_msgs = new_next_msgs;
4123                                 }
4124                         }
4125                 }
4126
4127                 let mut prev_node = expected_route.last().unwrap();
4128                 for (idx, node) in expected_route.iter().rev().enumerate() {
4129                         assert_eq!(expected_next_node, node.node.get_our_node_id());
4130                         let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
4131                         if next_msgs.is_some() {
4132                                 mid_update_fulfill_dance!(node, prev_node, update_next_msgs);
4133                         } else if update_next_msgs {
4134                                 next_msgs = get_next_msgs!(node);
4135                         } else {
4136                                 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
4137                         }
4138                         if !skip_last && idx == expected_route.len() - 1 {
4139                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4140                         }
4141
4142                         prev_node = node;
4143                 }
4144
4145                 if !skip_last {
4146                         last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
4147                         let events = origin_node.node.get_and_clear_pending_events();
4148                         assert_eq!(events.len(), 1);
4149                         match events[0] {
4150                                 Event::PaymentSent { payment_preimage } => {
4151                                         assert_eq!(payment_preimage, our_payment_preimage);
4152                                 },
4153                                 _ => panic!("Unexpected event"),
4154                         }
4155                 }
4156         }
4157
4158         fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: PaymentPreimage) {
4159                 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage);
4160         }
4161
4162         const TEST_FINAL_CLTV: u32 = 32;
4163
4164         fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
4165                 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();
4166                 assert_eq!(route.hops.len(), expected_route.len());
4167                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4168                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
4169                 }
4170
4171                 send_along_route(origin_node, route, expected_route, recv_value)
4172         }
4173
4174         fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
4175                 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();
4176                 assert_eq!(route.hops.len(), expected_route.len());
4177                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4178                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
4179                 }
4180
4181                 let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4182
4183                 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
4184                 match err {
4185                         APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
4186                         _ => panic!("Unknown error variants"),
4187                 };
4188         }
4189
4190         fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
4191                 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
4192                 claim_payment(&origin, expected_route, our_payment_preimage);
4193         }
4194
4195         fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: PaymentHash) {
4196                 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash, 0));
4197                 check_added_monitors!(expected_route.last().unwrap(), 1);
4198
4199                 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
4200                 macro_rules! update_fail_dance {
4201                         ($node: expr, $prev_node: expr, $last_node: expr) => {
4202                                 {
4203                                         $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4204                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
4205                                 }
4206                         }
4207                 }
4208
4209                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4210                 let mut prev_node = expected_route.last().unwrap();
4211                 for (idx, node) in expected_route.iter().rev().enumerate() {
4212                         assert_eq!(expected_next_node, node.node.get_our_node_id());
4213                         if next_msgs.is_some() {
4214                                 // We may be the "last node" for the purpose of the commitment dance if we're
4215                                 // skipping the last node (implying it is disconnected) and we're the
4216                                 // second-to-last node!
4217                                 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
4218                         }
4219
4220                         let events = node.node.get_and_clear_pending_msg_events();
4221                         if !skip_last || idx != expected_route.len() - 1 {
4222                                 assert_eq!(events.len(), 1);
4223                                 match events[0] {
4224                                         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 } } => {
4225                                                 assert!(update_add_htlcs.is_empty());
4226                                                 assert!(update_fulfill_htlcs.is_empty());
4227                                                 assert_eq!(update_fail_htlcs.len(), 1);
4228                                                 assert!(update_fail_malformed_htlcs.is_empty());
4229                                                 assert!(update_fee.is_none());
4230                                                 expected_next_node = node_id.clone();
4231                                                 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
4232                                         },
4233                                         _ => panic!("Unexpected event"),
4234                                 }
4235                         } else {
4236                                 assert!(events.is_empty());
4237                         }
4238                         if !skip_last && idx == expected_route.len() - 1 {
4239                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4240                         }
4241
4242                         prev_node = node;
4243                 }
4244
4245                 if !skip_last {
4246                         update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
4247
4248                         let events = origin_node.node.get_and_clear_pending_events();
4249                         assert_eq!(events.len(), 1);
4250                         match events[0] {
4251                                 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
4252                                         assert_eq!(payment_hash, our_payment_hash);
4253                                         assert!(rejected_by_dest);
4254                                 },
4255                                 _ => panic!("Unexpected event"),
4256                         }
4257                 }
4258         }
4259
4260         fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: PaymentHash) {
4261                 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
4262         }
4263
4264         fn create_network(node_count: usize) -> Vec<Node> {
4265                 let mut nodes = Vec::new();
4266                 let mut rng = thread_rng();
4267                 let secp_ctx = Secp256k1::new();
4268
4269                 let chan_count = Rc::new(RefCell::new(0));
4270                 let payment_count = Rc::new(RefCell::new(0));
4271
4272                 for i in 0..node_count {
4273                         let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
4274                         let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
4275                         let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
4276                         let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
4277                         let mut seed = [0; 32];
4278                         rng.fill_bytes(&mut seed);
4279                         let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&seed, Network::Testnet, Arc::clone(&logger)));
4280                         let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone()));
4281                         let mut config = UserConfig::new();
4282                         config.channel_options.announced_channel = true;
4283                         config.channel_limits.force_announced_channel_preference = false;
4284                         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();
4285                         let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), chain_monitor.clone(), Arc::clone(&logger));
4286                         nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router, keys_manager, node_seed: seed,
4287                                 network_payment_count: payment_count.clone(),
4288                                 network_chan_count: chan_count.clone(),
4289                         });
4290                 }
4291
4292                 nodes
4293         }
4294
4295         #[test]
4296         fn test_async_inbound_update_fee() {
4297                 let mut nodes = create_network(2);
4298                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4299                 let channel_id = chan.2;
4300
4301                 // balancing
4302                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4303
4304                 // A                                        B
4305                 // update_fee                            ->
4306                 // send (1) commitment_signed            -.
4307                 //                                       <- update_add_htlc/commitment_signed
4308                 // send (2) RAA (awaiting remote revoke) -.
4309                 // (1) commitment_signed is delivered    ->
4310                 //                                       .- send (3) RAA (awaiting remote revoke)
4311                 // (2) RAA is delivered                  ->
4312                 //                                       .- send (4) commitment_signed
4313                 //                                       <- (3) RAA is delivered
4314                 // send (5) commitment_signed            -.
4315                 //                                       <- (4) commitment_signed is delivered
4316                 // send (6) RAA                          -.
4317                 // (5) commitment_signed is delivered    ->
4318                 //                                       <- RAA
4319                 // (6) RAA is delivered                  ->
4320
4321                 // First nodes[0] generates an update_fee
4322                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4323                 check_added_monitors!(nodes[0], 1);
4324
4325                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4326                 assert_eq!(events_0.len(), 1);
4327                 let (update_msg, commitment_signed) = match events_0[0] { // (1)
4328                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4329                                 (update_fee.as_ref(), commitment_signed)
4330                         },
4331                         _ => panic!("Unexpected event"),
4332                 };
4333
4334                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4335
4336                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4337                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4338                 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();
4339                 check_added_monitors!(nodes[1], 1);
4340
4341                 let payment_event = {
4342                         let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4343                         assert_eq!(events_1.len(), 1);
4344                         SendEvent::from_event(events_1.remove(0))
4345                 };
4346                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4347                 assert_eq!(payment_event.msgs.len(), 1);
4348
4349                 // ...now when the messages get delivered everyone should be happy
4350                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4351                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4352                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4353                 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4354                 check_added_monitors!(nodes[0], 1);
4355
4356                 // deliver(1), generate (3):
4357                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4358                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4359                 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
4360                 check_added_monitors!(nodes[1], 1);
4361
4362                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap(); // deliver (2)
4363                 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4364                 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
4365                 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
4366                 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
4367                 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
4368                 assert!(bs_update.update_fee.is_none()); // (4)
4369                 check_added_monitors!(nodes[1], 1);
4370
4371                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap(); // deliver (3)
4372                 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4373                 assert!(as_update.update_add_htlcs.is_empty()); // (5)
4374                 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
4375                 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
4376                 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
4377                 assert!(as_update.update_fee.is_none()); // (5)
4378                 check_added_monitors!(nodes[0], 1);
4379
4380                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed).unwrap(); // deliver (4)
4381                 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4382                 // only (6) so get_event_msg's assert(len == 1) passes
4383                 check_added_monitors!(nodes[0], 1);
4384
4385                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed).unwrap(); // deliver (5)
4386                 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4387                 check_added_monitors!(nodes[1], 1);
4388
4389                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4390                 check_added_monitors!(nodes[0], 1);
4391
4392                 let events_2 = nodes[0].node.get_and_clear_pending_events();
4393                 assert_eq!(events_2.len(), 1);
4394                 match events_2[0] {
4395                         Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
4396                         _ => panic!("Unexpected event"),
4397                 }
4398
4399                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap(); // deliver (6)
4400                 check_added_monitors!(nodes[1], 1);
4401         }
4402
4403         #[test]
4404         fn test_update_fee_unordered_raa() {
4405                 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
4406                 // crash in an earlier version of the update_fee patch)
4407                 let mut nodes = create_network(2);
4408                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4409                 let channel_id = chan.2;
4410
4411                 // balancing
4412                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4413
4414                 // First nodes[0] generates an update_fee
4415                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4416                 check_added_monitors!(nodes[0], 1);
4417
4418                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4419                 assert_eq!(events_0.len(), 1);
4420                 let update_msg = match events_0[0] { // (1)
4421                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
4422                                 update_fee.as_ref()
4423                         },
4424                         _ => panic!("Unexpected event"),
4425                 };
4426
4427                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4428
4429                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4430                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4431                 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();
4432                 check_added_monitors!(nodes[1], 1);
4433
4434                 let payment_event = {
4435                         let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4436                         assert_eq!(events_1.len(), 1);
4437                         SendEvent::from_event(events_1.remove(0))
4438                 };
4439                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4440                 assert_eq!(payment_event.msgs.len(), 1);
4441
4442                 // ...now when the messages get delivered everyone should be happy
4443                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4444                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4445                 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4446                 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4447                 check_added_monitors!(nodes[0], 1);
4448
4449                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap(); // deliver (2)
4450                 check_added_monitors!(nodes[1], 1);
4451
4452                 // We can't continue, sadly, because our (1) now has a bogus signature
4453         }
4454
4455         #[test]
4456         fn test_multi_flight_update_fee() {
4457                 let nodes = create_network(2);
4458                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4459                 let channel_id = chan.2;
4460
4461                 // A                                        B
4462                 // update_fee/commitment_signed          ->
4463                 //                                       .- send (1) RAA and (2) commitment_signed
4464                 // update_fee (never committed)          ->
4465                 // (3) update_fee                        ->
4466                 // We have to manually generate the above update_fee, it is allowed by the protocol but we
4467                 // don't track which updates correspond to which revoke_and_ack responses so we're in
4468                 // AwaitingRAA mode and will not generate the update_fee yet.
4469                 //                                       <- (1) RAA delivered
4470                 // (3) is generated and send (4) CS      -.
4471                 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
4472                 // know the per_commitment_point to use for it.
4473                 //                                       <- (2) commitment_signed delivered
4474                 // revoke_and_ack                        ->
4475                 //                                          B should send no response here
4476                 // (4) commitment_signed delivered       ->
4477                 //                                       <- RAA/commitment_signed delivered
4478                 // revoke_and_ack                        ->
4479
4480                 // First nodes[0] generates an update_fee
4481                 let initial_feerate = get_feerate!(nodes[0], channel_id);
4482                 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
4483                 check_added_monitors!(nodes[0], 1);
4484
4485                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4486                 assert_eq!(events_0.len(), 1);
4487                 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
4488                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4489                                 (update_fee.as_ref().unwrap(), commitment_signed)
4490                         },
4491                         _ => panic!("Unexpected event"),
4492                 };
4493
4494                 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
4495                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1).unwrap();
4496                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1).unwrap();
4497                 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4498                 check_added_monitors!(nodes[1], 1);
4499
4500                 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
4501                 // transaction:
4502                 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
4503                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4504                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4505
4506                 // Create the (3) update_fee message that nodes[0] will generate before it does...
4507                 let mut update_msg_2 = msgs::UpdateFee {
4508                         channel_id: update_msg_1.channel_id.clone(),
4509                         feerate_per_kw: (initial_feerate + 30) as u32,
4510                 };
4511
4512                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4513
4514                 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
4515                 // Deliver (3)
4516                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4517
4518                 // Deliver (1), generating (3) and (4)
4519                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap();
4520                 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4521                 check_added_monitors!(nodes[0], 1);
4522                 assert!(as_second_update.update_add_htlcs.is_empty());
4523                 assert!(as_second_update.update_fulfill_htlcs.is_empty());
4524                 assert!(as_second_update.update_fail_htlcs.is_empty());
4525                 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
4526                 // Check that the update_fee newly generated matches what we delivered:
4527                 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
4528                 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
4529
4530                 // Deliver (2) commitment_signed
4531                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
4532                 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4533                 check_added_monitors!(nodes[0], 1);
4534                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4535
4536                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap();
4537                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4538                 check_added_monitors!(nodes[1], 1);
4539
4540                 // Delever (4)
4541                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed).unwrap();
4542                 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4543                 check_added_monitors!(nodes[1], 1);
4544
4545                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4546                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4547                 check_added_monitors!(nodes[0], 1);
4548
4549                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment).unwrap();
4550                 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4551                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4552                 check_added_monitors!(nodes[0], 1);
4553
4554                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap();
4555                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4556                 check_added_monitors!(nodes[1], 1);
4557         }
4558
4559         #[test]
4560         fn test_update_fee_vanilla() {
4561                 let nodes = create_network(2);
4562                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4563                 let channel_id = chan.2;
4564
4565                 let feerate = get_feerate!(nodes[0], channel_id);
4566                 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
4567                 check_added_monitors!(nodes[0], 1);
4568
4569                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4570                 assert_eq!(events_0.len(), 1);
4571                 let (update_msg, commitment_signed) = match events_0[0] {
4572                                 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 } } => {
4573                                 (update_fee.as_ref(), commitment_signed)
4574                         },
4575                         _ => panic!("Unexpected event"),
4576                 };
4577                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4578
4579                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4580                 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4581                 check_added_monitors!(nodes[1], 1);
4582
4583                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4584                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4585                 check_added_monitors!(nodes[0], 1);
4586
4587                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4588                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4589                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4590                 check_added_monitors!(nodes[0], 1);
4591
4592                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4593                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4594                 check_added_monitors!(nodes[1], 1);
4595         }
4596
4597         #[test]
4598         fn test_update_fee_that_funder_cannot_afford() {
4599                 let nodes = create_network(2);
4600                 let channel_value = 1888;
4601                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000);
4602                 let channel_id = chan.2;
4603
4604                 let feerate = 260;
4605                 nodes[0].node.update_fee(channel_id, feerate).unwrap();
4606                 check_added_monitors!(nodes[0], 1);
4607                 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4608
4609                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap()).unwrap();
4610
4611                 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
4612
4613                 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
4614                 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
4615                 {
4616                         let chan_lock = nodes[1].node.channel_state.lock().unwrap();
4617                         let chan = chan_lock.by_id.get(&channel_id).unwrap();
4618
4619                         //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
4620                         let num_htlcs = chan.last_local_commitment_txn[0].output.len() - 2;
4621                         let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
4622                         let mut actual_fee = chan.last_local_commitment_txn[0].output.iter().fold(0, |acc, output| acc + output.value);
4623                         actual_fee = channel_value - actual_fee;
4624                         assert_eq!(total_fee, actual_fee);
4625                 } //drop the mutex
4626
4627                 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
4628                 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
4629                 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
4630                 check_added_monitors!(nodes[0], 1);
4631
4632                 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4633
4634                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap()).unwrap();
4635
4636                 //While producing the commitment_signed response after handling a received update_fee request the
4637                 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
4638                 //Should produce and error.
4639                 let err = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed).unwrap_err();
4640
4641                 assert!(match err.err {
4642                         "Funding remote cannot afford proposed new fee" => true,
4643                         _ => false,
4644                 });
4645
4646                 //clear the message we could not handle
4647                 nodes[1].node.get_and_clear_pending_msg_events();
4648         }
4649
4650         #[test]
4651         fn test_update_fee_with_fundee_update_add_htlc() {
4652                 let mut nodes = create_network(2);
4653                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4654                 let channel_id = chan.2;
4655
4656                 // balancing
4657                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4658
4659                 let feerate = get_feerate!(nodes[0], channel_id);
4660                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4661                 check_added_monitors!(nodes[0], 1);
4662
4663                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4664                 assert_eq!(events_0.len(), 1);
4665                 let (update_msg, commitment_signed) = match events_0[0] {
4666                                 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 } } => {
4667                                 (update_fee.as_ref(), commitment_signed)
4668                         },
4669                         _ => panic!("Unexpected event"),
4670                 };
4671                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4672                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4673                 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4674                 check_added_monitors!(nodes[1], 1);
4675
4676                 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
4677
4678                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
4679
4680                 // nothing happens since node[1] is in AwaitingRemoteRevoke
4681                 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
4682                 {
4683                         let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
4684                         assert_eq!(added_monitors.len(), 0);
4685                         added_monitors.clear();
4686                 }
4687                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4688                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4689                 // node[1] has nothing to do
4690
4691                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4692                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4693                 check_added_monitors!(nodes[0], 1);
4694
4695                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4696                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4697                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4698                 check_added_monitors!(nodes[0], 1);
4699                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4700                 check_added_monitors!(nodes[1], 1);
4701                 // AwaitingRemoteRevoke ends here
4702
4703                 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4704                 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
4705                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
4706                 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
4707                 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
4708                 assert_eq!(commitment_update.update_fee.is_none(), true);
4709
4710                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]).unwrap();
4711                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4712                 check_added_monitors!(nodes[0], 1);
4713                 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4714
4715                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke).unwrap();
4716                 check_added_monitors!(nodes[1], 1);
4717                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4718
4719                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed).unwrap();
4720                 check_added_monitors!(nodes[1], 1);
4721                 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4722                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4723
4724                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke).unwrap();
4725                 check_added_monitors!(nodes[0], 1);
4726                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4727
4728                 let events = nodes[0].node.get_and_clear_pending_events();
4729                 assert_eq!(events.len(), 1);
4730                 match events[0] {
4731                         Event::PendingHTLCsForwardable { .. } => { },
4732                         _ => panic!("Unexpected event"),
4733                 };
4734                 nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
4735                 nodes[0].node.process_pending_htlc_forwards();
4736
4737                 let events = nodes[0].node.get_and_clear_pending_events();
4738                 assert_eq!(events.len(), 1);
4739                 match events[0] {
4740                         Event::PaymentReceived { .. } => { },
4741                         _ => panic!("Unexpected event"),
4742                 };
4743
4744                 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
4745
4746                 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
4747                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
4748                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4749         }
4750
4751         #[test]
4752         fn test_update_fee() {
4753                 let nodes = create_network(2);
4754                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4755                 let channel_id = chan.2;
4756
4757                 // A                                        B
4758                 // (1) update_fee/commitment_signed      ->
4759                 //                                       <- (2) revoke_and_ack
4760                 //                                       .- send (3) commitment_signed
4761                 // (4) update_fee/commitment_signed      ->
4762                 //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
4763                 //                                       <- (3) commitment_signed delivered
4764                 // send (6) revoke_and_ack               -.
4765                 //                                       <- (5) deliver revoke_and_ack
4766                 // (6) deliver revoke_and_ack            ->
4767                 //                                       .- send (7) commitment_signed in response to (4)
4768                 //                                       <- (7) deliver commitment_signed
4769                 // revoke_and_ack                        ->
4770
4771                 // Create and deliver (1)...
4772                 let feerate = get_feerate!(nodes[0], channel_id);
4773                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4774                 check_added_monitors!(nodes[0], 1);
4775
4776                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4777                 assert_eq!(events_0.len(), 1);
4778                 let (update_msg, commitment_signed) = match events_0[0] {
4779                                 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 } } => {
4780                                 (update_fee.as_ref(), commitment_signed)
4781                         },
4782                         _ => panic!("Unexpected event"),
4783                 };
4784                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4785
4786                 // Generate (2) and (3):
4787                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4788                 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4789                 check_added_monitors!(nodes[1], 1);
4790
4791                 // Deliver (2):
4792                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4793                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4794                 check_added_monitors!(nodes[0], 1);
4795
4796                 // Create and deliver (4)...
4797                 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
4798                 check_added_monitors!(nodes[0], 1);
4799                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4800                 assert_eq!(events_0.len(), 1);
4801                 let (update_msg, commitment_signed) = match events_0[0] {
4802                                 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 } } => {
4803                                 (update_fee.as_ref(), commitment_signed)
4804                         },
4805                         _ => panic!("Unexpected event"),
4806                 };
4807
4808                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4809                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4810                 check_added_monitors!(nodes[1], 1);
4811                 // ... creating (5)
4812                 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4813                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4814
4815                 // Handle (3), creating (6):
4816                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0).unwrap();
4817                 check_added_monitors!(nodes[0], 1);
4818                 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4819                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4820
4821                 // Deliver (5):
4822                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4823                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4824                 check_added_monitors!(nodes[0], 1);
4825
4826                 // Deliver (6), creating (7):
4827                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0).unwrap();
4828                 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4829                 assert!(commitment_update.update_add_htlcs.is_empty());
4830                 assert!(commitment_update.update_fulfill_htlcs.is_empty());
4831                 assert!(commitment_update.update_fail_htlcs.is_empty());
4832                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
4833                 assert!(commitment_update.update_fee.is_none());
4834                 check_added_monitors!(nodes[1], 1);
4835
4836                 // Deliver (7)
4837                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4838                 check_added_monitors!(nodes[0], 1);
4839                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4840                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4841
4842                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4843                 check_added_monitors!(nodes[1], 1);
4844                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4845
4846                 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
4847                 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
4848                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4849         }
4850
4851         #[test]
4852         fn pre_funding_lock_shutdown_test() {
4853                 // Test sending a shutdown prior to funding_locked after funding generation
4854                 let nodes = create_network(2);
4855                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0);
4856                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4857                 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4858                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4859
4860                 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
4861                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4862                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4863                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4864                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4865
4866                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4867                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4868                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4869                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4870                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4871                 assert!(node_0_none.is_none());
4872
4873                 assert!(nodes[0].node.list_channels().is_empty());
4874                 assert!(nodes[1].node.list_channels().is_empty());
4875         }
4876
4877         #[test]
4878         fn updates_shutdown_wait() {
4879                 // Test sending a shutdown with outstanding updates pending
4880                 let mut nodes = create_network(3);
4881                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4882                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4883                 let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4884                 let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4885
4886                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
4887
4888                 nodes[0].node.close_channel(&chan_1.2).unwrap();
4889                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4890                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4891                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4892                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4893
4894                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4895                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4896
4897                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4898                 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route_1, payment_hash) {}
4899                 else { panic!("New sends should fail!") };
4900                 if let Err(APIError::ChannelUnavailable {..}) = nodes[1].node.send_payment(route_2, payment_hash) {}
4901                 else { panic!("New sends should fail!") };
4902
4903                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
4904                 check_added_monitors!(nodes[2], 1);
4905                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4906                 assert!(updates.update_add_htlcs.is_empty());
4907                 assert!(updates.update_fail_htlcs.is_empty());
4908                 assert!(updates.update_fail_malformed_htlcs.is_empty());
4909                 assert!(updates.update_fee.is_none());
4910                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4911                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
4912                 check_added_monitors!(nodes[1], 1);
4913                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4914                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
4915
4916                 assert!(updates_2.update_add_htlcs.is_empty());
4917                 assert!(updates_2.update_fail_htlcs.is_empty());
4918                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
4919                 assert!(updates_2.update_fee.is_none());
4920                 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
4921                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
4922                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
4923
4924                 let events = nodes[0].node.get_and_clear_pending_events();
4925                 assert_eq!(events.len(), 1);
4926                 match events[0] {
4927                         Event::PaymentSent { ref payment_preimage } => {
4928                                 assert_eq!(our_payment_preimage, *payment_preimage);
4929                         },
4930                         _ => panic!("Unexpected event"),
4931                 }
4932
4933                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4934                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4935                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4936                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4937                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4938                 assert!(node_0_none.is_none());
4939
4940                 assert!(nodes[0].node.list_channels().is_empty());
4941
4942                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4943                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
4944                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
4945                 assert!(nodes[1].node.list_channels().is_empty());
4946                 assert!(nodes[2].node.list_channels().is_empty());
4947         }
4948
4949         #[test]
4950         fn htlc_fail_async_shutdown() {
4951                 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
4952                 let mut nodes = create_network(3);
4953                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4954                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4955
4956                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4957                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4958                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
4959                 check_added_monitors!(nodes[0], 1);
4960                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4961                 assert_eq!(updates.update_add_htlcs.len(), 1);
4962                 assert!(updates.update_fulfill_htlcs.is_empty());
4963                 assert!(updates.update_fail_htlcs.is_empty());
4964                 assert!(updates.update_fail_malformed_htlcs.is_empty());
4965                 assert!(updates.update_fee.is_none());
4966
4967                 nodes[1].node.close_channel(&chan_1.2).unwrap();
4968                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4969                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4970                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4971
4972                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
4973                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
4974                 check_added_monitors!(nodes[1], 1);
4975                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4976                 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
4977
4978                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4979                 assert!(updates_2.update_add_htlcs.is_empty());
4980                 assert!(updates_2.update_fulfill_htlcs.is_empty());
4981                 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
4982                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
4983                 assert!(updates_2.update_fee.is_none());
4984
4985                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]).unwrap();
4986                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
4987
4988                 let events = nodes[0].node.get_and_clear_pending_events();
4989                 assert_eq!(events.len(), 1);
4990                 match events[0] {
4991                         Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } => {
4992                                 assert_eq!(our_payment_hash, *payment_hash);
4993                                 assert!(!rejected_by_dest);
4994                         },
4995                         _ => panic!("Unexpected event"),
4996                 }
4997
4998                 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4999                 assert_eq!(msg_events.len(), 2);
5000                 let node_0_closing_signed = match msg_events[0] {
5001                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
5002                                 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5003                                 (*msg).clone()
5004                         },
5005                         _ => panic!("Unexpected event"),
5006                 };
5007                 match msg_events[1] {
5008                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
5009                                 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
5010                         },
5011                         _ => panic!("Unexpected event"),
5012                 }
5013
5014                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5015                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5016                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5017                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5018                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5019                 assert!(node_0_none.is_none());
5020
5021                 assert!(nodes[0].node.list_channels().is_empty());
5022
5023                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5024                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5025                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5026                 assert!(nodes[1].node.list_channels().is_empty());
5027                 assert!(nodes[2].node.list_channels().is_empty());
5028         }
5029
5030         fn do_test_shutdown_rebroadcast(recv_count: u8) {
5031                 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
5032                 // messages delivered prior to disconnect
5033                 let nodes = create_network(3);
5034                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5035                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5036
5037                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
5038
5039                 nodes[1].node.close_channel(&chan_1.2).unwrap();
5040                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5041                 if recv_count > 0 {
5042                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
5043                         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5044                         if recv_count > 1 {
5045                                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
5046                         }
5047                 }
5048
5049                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5050                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5051
5052                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5053                 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5054                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5055                 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5056
5057                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish).unwrap();
5058                 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5059                 assert!(node_1_shutdown == node_1_2nd_shutdown);
5060
5061                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish).unwrap();
5062                 let node_0_2nd_shutdown = if recv_count > 0 {
5063                         let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5064                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5065                         node_0_2nd_shutdown
5066                 } else {
5067                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5068                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5069                         get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
5070                 };
5071                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown).unwrap();
5072
5073                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5074                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5075
5076                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
5077                 check_added_monitors!(nodes[2], 1);
5078                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5079                 assert!(updates.update_add_htlcs.is_empty());
5080                 assert!(updates.update_fail_htlcs.is_empty());
5081                 assert!(updates.update_fail_malformed_htlcs.is_empty());
5082                 assert!(updates.update_fee.is_none());
5083                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5084                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
5085                 check_added_monitors!(nodes[1], 1);
5086                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5087                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
5088
5089                 assert!(updates_2.update_add_htlcs.is_empty());
5090                 assert!(updates_2.update_fail_htlcs.is_empty());
5091                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
5092                 assert!(updates_2.update_fee.is_none());
5093                 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
5094                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
5095                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
5096
5097                 let events = nodes[0].node.get_and_clear_pending_events();
5098                 assert_eq!(events.len(), 1);
5099                 match events[0] {
5100                         Event::PaymentSent { ref payment_preimage } => {
5101                                 assert_eq!(our_payment_preimage, *payment_preimage);
5102                         },
5103                         _ => panic!("Unexpected event"),
5104                 }
5105
5106                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5107                 if recv_count > 0 {
5108                         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5109                         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5110                         assert!(node_1_closing_signed.is_some());
5111                 }
5112
5113                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5114                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5115
5116                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5117                 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5118                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5119                 if recv_count == 0 {
5120                         // If all closing_signeds weren't delivered we can just resume where we left off...
5121                         let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5122
5123                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish).unwrap();
5124                         let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5125                         assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
5126
5127                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish).unwrap();
5128                         let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5129                         assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
5130
5131                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown).unwrap();
5132                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5133
5134                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown).unwrap();
5135                         let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5136                         assert!(node_0_closing_signed == node_0_2nd_closing_signed);
5137
5138                         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed).unwrap();
5139                         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5140                         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5141                         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5142                         assert!(node_0_none.is_none());
5143                 } else {
5144                         // If one node, however, received + responded with an identical closing_signed we end
5145                         // up erroring and node[0] will try to broadcast its own latest commitment transaction.
5146                         // There isn't really anything better we can do simply, but in the future we might
5147                         // explore storing a set of recently-closed channels that got disconnected during
5148                         // closing_signed and avoiding broadcasting local commitment txn for some timeout to
5149                         // give our counterparty enough time to (potentially) broadcast a cooperative closing
5150                         // transaction.
5151                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5152
5153                         if let Err(msgs::HandleError{action: Some(msgs::ErrorAction::SendErrorMessage{msg}), ..}) =
5154                                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish) {
5155                                 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
5156                                 let msgs::ErrorMessage {ref channel_id, ..} = msg;
5157                                 assert_eq!(*channel_id, chan_1.2);
5158                         } else { panic!("Needed SendErrorMessage close"); }
5159
5160                         // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
5161                         // checks it, but in this case nodes[0] didn't ever get a chance to receive a
5162                         // closing_signed so we do it ourselves
5163                         let events = nodes[0].node.get_and_clear_pending_msg_events();
5164                         assert_eq!(events.len(), 1);
5165                         match events[0] {
5166                                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5167                                         assert_eq!(msg.contents.flags & 2, 2);
5168                                 },
5169                                 _ => panic!("Unexpected event"),
5170                         }
5171                 }
5172
5173                 assert!(nodes[0].node.list_channels().is_empty());
5174
5175                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5176                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5177                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5178                 assert!(nodes[1].node.list_channels().is_empty());
5179                 assert!(nodes[2].node.list_channels().is_empty());
5180         }
5181
5182         #[test]
5183         fn test_shutdown_rebroadcast() {
5184                 do_test_shutdown_rebroadcast(0);
5185                 do_test_shutdown_rebroadcast(1);
5186                 do_test_shutdown_rebroadcast(2);
5187         }
5188
5189         #[test]
5190         fn fake_network_test() {
5191                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5192                 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
5193                 let nodes = create_network(4);
5194
5195                 // Create some initial channels
5196                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5197                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5198                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5199
5200                 // Rebalance the network a bit by relaying one payment through all the channels...
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                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5205
5206                 // Send some more payments
5207                 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
5208                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
5209                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
5210
5211                 // Test failure packets
5212                 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
5213                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
5214
5215                 // Add a new channel that skips 3
5216                 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
5217
5218                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
5219                 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
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                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5225
5226                 // Do some rebalance loop payments, simultaneously
5227                 let mut hops = Vec::with_capacity(3);
5228                 hops.push(RouteHop {
5229                         pubkey: nodes[2].node.get_our_node_id(),
5230                         short_channel_id: chan_2.0.contents.short_channel_id,
5231                         fee_msat: 0,
5232                         cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
5233                 });
5234                 hops.push(RouteHop {
5235                         pubkey: nodes[3].node.get_our_node_id(),
5236                         short_channel_id: chan_3.0.contents.short_channel_id,
5237                         fee_msat: 0,
5238                         cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
5239                 });
5240                 hops.push(RouteHop {
5241                         pubkey: nodes[1].node.get_our_node_id(),
5242                         short_channel_id: chan_4.0.contents.short_channel_id,
5243                         fee_msat: 1000000,
5244                         cltv_expiry_delta: TEST_FINAL_CLTV,
5245                 });
5246                 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;
5247                 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;
5248                 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
5249
5250                 let mut hops = Vec::with_capacity(3);
5251                 hops.push(RouteHop {
5252                         pubkey: nodes[3].node.get_our_node_id(),
5253                         short_channel_id: chan_4.0.contents.short_channel_id,
5254                         fee_msat: 0,
5255                         cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
5256                 });
5257                 hops.push(RouteHop {
5258                         pubkey: nodes[2].node.get_our_node_id(),
5259                         short_channel_id: chan_3.0.contents.short_channel_id,
5260                         fee_msat: 0,
5261                         cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
5262                 });
5263                 hops.push(RouteHop {
5264                         pubkey: nodes[1].node.get_our_node_id(),
5265                         short_channel_id: chan_2.0.contents.short_channel_id,
5266                         fee_msat: 1000000,
5267                         cltv_expiry_delta: TEST_FINAL_CLTV,
5268                 });
5269                 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;
5270                 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;
5271                 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
5272
5273                 // Claim the rebalances...
5274                 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
5275                 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
5276
5277                 // Add a duplicate new channel from 2 to 4
5278                 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3);
5279
5280                 // Send some payments across both channels
5281                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5282                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5283                 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5284
5285                 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
5286
5287                 //TODO: Test that routes work again here as we've been notified that the channel is full
5288
5289                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
5290                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
5291                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
5292
5293                 // Close down the channels...
5294                 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
5295                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
5296                 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
5297                 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
5298                 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
5299         }
5300
5301         #[test]
5302         fn duplicate_htlc_test() {
5303                 // Test that we accept duplicate payment_hash HTLCs across the network and that
5304                 // claiming/failing them are all separate and don't effect each other
5305                 let mut nodes = create_network(6);
5306
5307                 // Create some initial channels to route via 3 to 4/5 from 0/1/2
5308                 create_announced_chan_between_nodes(&nodes, 0, 3);
5309                 create_announced_chan_between_nodes(&nodes, 1, 3);
5310                 create_announced_chan_between_nodes(&nodes, 2, 3);
5311                 create_announced_chan_between_nodes(&nodes, 3, 4);
5312                 create_announced_chan_between_nodes(&nodes, 3, 5);
5313
5314                 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
5315
5316                 *nodes[0].network_payment_count.borrow_mut() -= 1;
5317                 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
5318
5319                 *nodes[0].network_payment_count.borrow_mut() -= 1;
5320                 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
5321
5322                 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
5323                 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
5324                 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
5325         }
5326
5327         #[derive(PartialEq)]
5328         enum HTLCType { NONE, TIMEOUT, SUCCESS }
5329         /// Tests that the given node has broadcast transactions for the given Channel
5330         ///
5331         /// First checks that the latest local commitment tx has been broadcast, unless an explicit
5332         /// commitment_tx is provided, which may be used to test that a remote commitment tx was
5333         /// broadcast and the revoked outputs were claimed.
5334         ///
5335         /// Next tests that there is (or is not) a transaction that spends the commitment transaction
5336         /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
5337         ///
5338         /// All broadcast transactions must be accounted for in one of the above three types of we'll
5339         /// also fail.
5340         fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
5341                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5342                 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
5343
5344                 let mut res = Vec::with_capacity(2);
5345                 node_txn.retain(|tx| {
5346                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
5347                                 check_spends!(tx, chan.3.clone());
5348                                 if commitment_tx.is_none() {
5349                                         res.push(tx.clone());
5350                                 }
5351                                 false
5352                         } else { true }
5353                 });
5354                 if let Some(explicit_tx) = commitment_tx {
5355                         res.push(explicit_tx.clone());
5356                 }
5357
5358                 assert_eq!(res.len(), 1);
5359
5360                 if has_htlc_tx != HTLCType::NONE {
5361                         node_txn.retain(|tx| {
5362                                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
5363                                         check_spends!(tx, res[0].clone());
5364                                         if has_htlc_tx == HTLCType::TIMEOUT {
5365                                                 assert!(tx.lock_time != 0);
5366                                         } else {
5367                                                 assert!(tx.lock_time == 0);
5368                                         }
5369                                         res.push(tx.clone());
5370                                         false
5371                                 } else { true }
5372                         });
5373                         assert!(res.len() == 2 || res.len() == 3);
5374                         if res.len() == 3 {
5375                                 assert_eq!(res[1], res[2]);
5376                         }
5377                 }
5378
5379                 assert!(node_txn.is_empty());
5380                 res
5381         }
5382
5383         /// Tests that the given node has broadcast a claim transaction against the provided revoked
5384         /// HTLC transaction.
5385         fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
5386                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5387                 assert_eq!(node_txn.len(), 1);
5388                 node_txn.retain(|tx| {
5389                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
5390                                 check_spends!(tx, revoked_tx.clone());
5391                                 false
5392                         } else { true }
5393                 });
5394                 assert!(node_txn.is_empty());
5395         }
5396
5397         fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
5398                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5399
5400                 assert!(node_txn.len() >= 1);
5401                 assert_eq!(node_txn[0].input.len(), 1);
5402                 let mut found_prev = false;
5403
5404                 for tx in prev_txn {
5405                         if node_txn[0].input[0].previous_output.txid == tx.txid() {
5406                                 check_spends!(node_txn[0], tx.clone());
5407                                 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
5408                                 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
5409
5410                                 found_prev = true;
5411                                 break;
5412                         }
5413                 }
5414                 assert!(found_prev);
5415
5416                 let mut res = Vec::new();
5417                 mem::swap(&mut *node_txn, &mut res);
5418                 res
5419         }
5420
5421         fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
5422                 let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
5423                 assert_eq!(events_1.len(), 1);
5424                 let as_update = match events_1[0] {
5425                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5426                                 msg.clone()
5427                         },
5428                         _ => panic!("Unexpected event"),
5429                 };
5430
5431                 let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
5432                 assert_eq!(events_2.len(), 1);
5433                 let bs_update = match events_2[0] {
5434                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5435                                 msg.clone()
5436                         },
5437                         _ => panic!("Unexpected event"),
5438                 };
5439
5440                 for node in nodes {
5441                         node.router.handle_channel_update(&as_update).unwrap();
5442                         node.router.handle_channel_update(&bs_update).unwrap();
5443                 }
5444         }
5445
5446         macro_rules! expect_pending_htlcs_forwardable {
5447                 ($node: expr) => {{
5448                         let events = $node.node.get_and_clear_pending_events();
5449                         assert_eq!(events.len(), 1);
5450                         match events[0] {
5451                                 Event::PendingHTLCsForwardable { .. } => { },
5452                                 _ => panic!("Unexpected event"),
5453                         };
5454                         $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
5455                         $node.node.process_pending_htlc_forwards();
5456                 }}
5457         }
5458
5459         fn do_channel_reserve_test(test_recv: bool) {
5460                 use util::rng;
5461                 use std::sync::atomic::Ordering;
5462                 use ln::msgs::HandleError;
5463
5464                 macro_rules! get_channel_value_stat {
5465                         ($node: expr, $channel_id: expr) => {{
5466                                 let chan_lock = $node.node.channel_state.lock().unwrap();
5467                                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
5468                                 chan.get_value_stat()
5469                         }}
5470                 }
5471
5472                 let mut nodes = create_network(3);
5473                 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001);
5474                 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001);
5475
5476                 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
5477                 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
5478
5479                 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
5480                 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
5481
5482                 macro_rules! get_route_and_payment_hash {
5483                         ($recv_value: expr) => {{
5484                                 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
5485                                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5486                                 (route, payment_hash, payment_preimage)
5487                         }}
5488                 };
5489
5490                 macro_rules! expect_forward {
5491                         ($node: expr) => {{
5492                                 let mut events = $node.node.get_and_clear_pending_msg_events();
5493                                 assert_eq!(events.len(), 1);
5494                                 check_added_monitors!($node, 1);
5495                                 let payment_event = SendEvent::from_event(events.remove(0));
5496                                 payment_event
5497                         }}
5498                 }
5499
5500                 macro_rules! expect_payment_received {
5501                         ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
5502                                 let events = $node.node.get_and_clear_pending_events();
5503                                 assert_eq!(events.len(), 1);
5504                                 match events[0] {
5505                                         Event::PaymentReceived { ref payment_hash, amt } => {
5506                                                 assert_eq!($expected_payment_hash, *payment_hash);
5507                                                 assert_eq!($expected_recv_value, amt);
5508                                         },
5509                                         _ => panic!("Unexpected event"),
5510                                 }
5511                         }
5512                 };
5513
5514                 let feemsat = 239; // somehow we know?
5515                 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
5516
5517                 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
5518
5519                 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
5520                 {
5521                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
5522                         assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
5523                         let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
5524                         match err {
5525                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
5526                                 _ => panic!("Unknown error variants"),
5527                         }
5528                 }
5529
5530                 let mut htlc_id = 0;
5531                 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
5532                 // nodes[0]'s wealth
5533                 loop {
5534                         let amt_msat = recv_value_0 + total_fee_msat;
5535                         if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
5536                                 break;
5537                         }
5538                         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
5539                         htlc_id += 1;
5540
5541                         let (stat01_, stat11_, stat12_, stat22_) = (
5542                                 get_channel_value_stat!(nodes[0], chan_1.2),
5543                                 get_channel_value_stat!(nodes[1], chan_1.2),
5544                                 get_channel_value_stat!(nodes[1], chan_2.2),
5545                                 get_channel_value_stat!(nodes[2], chan_2.2),
5546                         );
5547
5548                         assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
5549                         assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
5550                         assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
5551                         assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
5552                         stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
5553                 }
5554
5555                 {
5556                         let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
5557                         // attempt to get channel_reserve violation
5558                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
5559                         let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
5560                         match err {
5561                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5562                                 _ => panic!("Unknown error variants"),
5563                         }
5564                 }
5565
5566                 // adding pending output
5567                 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
5568                 let amt_msat_1 = recv_value_1 + total_fee_msat;
5569
5570                 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
5571                 let payment_event_1 = {
5572                         nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
5573                         check_added_monitors!(nodes[0], 1);
5574
5575                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5576                         assert_eq!(events.len(), 1);
5577                         SendEvent::from_event(events.remove(0))
5578                 };
5579                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]).unwrap();
5580
5581                 // channel reserve test with htlc pending output > 0
5582                 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
5583                 {
5584                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5585                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5586                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5587                                 _ => panic!("Unknown error variants"),
5588                         }
5589                 }
5590
5591                 {
5592                         // test channel_reserve test on nodes[1] side
5593                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5594
5595                         // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
5596                         let secp_ctx = Secp256k1::new();
5597                         let session_priv = SecretKey::from_slice(&secp_ctx, &{
5598                                 let mut session_key = [0; 32];
5599                                 rng::fill_bytes(&mut session_key);
5600                                 session_key
5601                         }).expect("RNG is bad!");
5602
5603                         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5604                         let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
5605                         let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height).unwrap();
5606                         let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
5607                         let msg = msgs::UpdateAddHTLC {
5608                                 channel_id: chan_1.2,
5609                                 htlc_id,
5610                                 amount_msat: htlc_msat,
5611                                 payment_hash: our_payment_hash,
5612                                 cltv_expiry: htlc_cltv,
5613                                 onion_routing_packet: onion_packet,
5614                         };
5615
5616                         if test_recv {
5617                                 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).err().unwrap();
5618                                 match err {
5619                                         HandleError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
5620                                 }
5621                                 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
5622                                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5623                                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5624                                 let channel_close_broadcast = nodes[1].node.get_and_clear_pending_msg_events();
5625                                 assert_eq!(channel_close_broadcast.len(), 1);
5626                                 match channel_close_broadcast[0] {
5627                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5628                                                 assert_eq!(msg.contents.flags & 2, 2);
5629                                         },
5630                                         _ => panic!("Unexpected event"),
5631                                 }
5632                                 return;
5633                         }
5634                 }
5635
5636                 // split the rest to test holding cell
5637                 let recv_value_21 = recv_value_2/2;
5638                 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
5639                 {
5640                         let stat = get_channel_value_stat!(nodes[0], chan_1.2);
5641                         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);
5642                 }
5643
5644                 // now see if they go through on both sides
5645                 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
5646                 // but this will stuck in the holding cell
5647                 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
5648                 check_added_monitors!(nodes[0], 0);
5649                 let events = nodes[0].node.get_and_clear_pending_events();
5650                 assert_eq!(events.len(), 0);
5651
5652                 // test with outbound holding cell amount > 0
5653                 {
5654                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
5655                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5656                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5657                                 _ => panic!("Unknown error variants"),
5658                         }
5659                 }
5660
5661                 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
5662                 // this will also stuck in the holding cell
5663                 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
5664                 check_added_monitors!(nodes[0], 0);
5665                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
5666                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5667
5668                 // flush the pending htlc
5669                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg).unwrap();
5670                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5671                 check_added_monitors!(nodes[1], 1);
5672
5673                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
5674                 check_added_monitors!(nodes[0], 1);
5675                 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5676
5677                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed).unwrap();
5678                 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
5679                 // No commitment_signed so get_event_msg's assert(len == 1) passes
5680                 check_added_monitors!(nodes[0], 1);
5681
5682                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
5683                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5684                 check_added_monitors!(nodes[1], 1);
5685
5686                 expect_pending_htlcs_forwardable!(nodes[1]);
5687
5688                 let ref payment_event_11 = expect_forward!(nodes[1]);
5689                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]).unwrap();
5690                 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
5691
5692                 expect_pending_htlcs_forwardable!(nodes[2]);
5693                 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
5694
5695                 // flush the htlcs in the holding cell
5696                 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
5697                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]).unwrap();
5698                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]).unwrap();
5699                 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
5700                 expect_pending_htlcs_forwardable!(nodes[1]);
5701
5702                 let ref payment_event_3 = expect_forward!(nodes[1]);
5703                 assert_eq!(payment_event_3.msgs.len(), 2);
5704                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]).unwrap();
5705                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]).unwrap();
5706
5707                 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
5708                 expect_pending_htlcs_forwardable!(nodes[2]);
5709
5710                 let events = nodes[2].node.get_and_clear_pending_events();
5711                 assert_eq!(events.len(), 2);
5712                 match events[0] {
5713                         Event::PaymentReceived { ref payment_hash, amt } => {
5714                                 assert_eq!(our_payment_hash_21, *payment_hash);
5715                                 assert_eq!(recv_value_21, amt);
5716                         },
5717                         _ => panic!("Unexpected event"),
5718                 }
5719                 match events[1] {
5720                         Event::PaymentReceived { ref payment_hash, amt } => {
5721                                 assert_eq!(our_payment_hash_22, *payment_hash);
5722                                 assert_eq!(recv_value_22, amt);
5723                         },
5724                         _ => panic!("Unexpected event"),
5725                 }
5726
5727                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
5728                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
5729                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
5730
5731                 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);
5732                 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
5733                 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
5734                 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
5735
5736                 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
5737                 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
5738         }
5739
5740         #[test]
5741         fn channel_reserve_test() {
5742                 do_channel_reserve_test(false);
5743                 do_channel_reserve_test(true);
5744         }
5745
5746         #[test]
5747         fn channel_monitor_network_test() {
5748                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5749                 // tests that ChannelMonitor is able to recover from various states.
5750                 let nodes = create_network(5);
5751
5752                 // Create some initial channels
5753                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5754                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5755                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5756                 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5757
5758                 // Rebalance the network a bit by relaying one payment through all the channels...
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                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5763
5764                 // Simple case with no pending HTLCs:
5765                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
5766                 {
5767                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
5768                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5769                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5770                         test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
5771                 }
5772                 get_announce_close_broadcast_events(&nodes, 0, 1);
5773                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5774                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5775
5776                 // One pending HTLC is discarded by the force-close:
5777                 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
5778
5779                 // Simple case of one pending HTLC to HTLC-Timeout
5780                 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
5781                 {
5782                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
5783                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5784                         nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5785                         test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
5786                 }
5787                 get_announce_close_broadcast_events(&nodes, 1, 2);
5788                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5789                 assert_eq!(nodes[2].node.list_channels().len(), 1);
5790
5791                 macro_rules! claim_funds {
5792                         ($node: expr, $prev_node: expr, $preimage: expr) => {
5793                                 {
5794                                         assert!($node.node.claim_funds($preimage));
5795                                         check_added_monitors!($node, 1);
5796
5797                                         let events = $node.node.get_and_clear_pending_msg_events();
5798                                         assert_eq!(events.len(), 1);
5799                                         match events[0] {
5800                                                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
5801                                                         assert!(update_add_htlcs.is_empty());
5802                                                         assert!(update_fail_htlcs.is_empty());
5803                                                         assert_eq!(*node_id, $prev_node.node.get_our_node_id());
5804                                                 },
5805                                                 _ => panic!("Unexpected event"),
5806                                         };
5807                                 }
5808                         }
5809                 }
5810
5811                 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
5812                 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
5813                 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
5814                 {
5815                         let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
5816
5817                         // Claim the payment on nodes[3], giving it knowledge of the preimage
5818                         claim_funds!(nodes[3], nodes[2], payment_preimage_1);
5819
5820                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5821                         nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
5822
5823                         check_preimage_claim(&nodes[3], &node_txn);
5824                 }
5825                 get_announce_close_broadcast_events(&nodes, 2, 3);
5826                 assert_eq!(nodes[2].node.list_channels().len(), 0);
5827                 assert_eq!(nodes[3].node.list_channels().len(), 1);
5828
5829                 { // Cheat and reset nodes[4]'s height to 1
5830                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5831                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![] }, 1);
5832                 }
5833
5834                 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
5835                 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
5836                 // One pending HTLC to time out:
5837                 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
5838                 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
5839                 // buffer space).
5840
5841                 {
5842                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5843                         nodes[3].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5844                         for i in 3..TEST_FINAL_CLTV + 2 + HTLC_FAIL_TIMEOUT_BLOCKS + 1 {
5845                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5846                                 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5847                         }
5848
5849                         let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
5850
5851                         // Claim the payment on nodes[4], giving it knowledge of the preimage
5852                         claim_funds!(nodes[4], nodes[3], payment_preimage_2);
5853
5854                         header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5855                         nodes[4].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5856                         for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
5857                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5858                                 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5859                         }
5860
5861                         test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
5862
5863                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5864                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
5865
5866                         check_preimage_claim(&nodes[4], &node_txn);
5867                 }
5868                 get_announce_close_broadcast_events(&nodes, 3, 4);
5869                 assert_eq!(nodes[3].node.list_channels().len(), 0);
5870                 assert_eq!(nodes[4].node.list_channels().len(), 0);
5871         }
5872
5873         #[test]
5874         fn test_justice_tx() {
5875                 // Test justice txn built on revoked HTLC-Success tx, against both sides
5876
5877                 let nodes = create_network(2);
5878                 // Create some new channels:
5879                 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
5880
5881                 // A pending HTLC which will be revoked:
5882                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5883                 // Get the will-be-revoked local txn from nodes[0]
5884                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5885                 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
5886                 assert_eq!(revoked_local_txn[0].input.len(), 1);
5887                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
5888                 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
5889                 assert_eq!(revoked_local_txn[1].input.len(), 1);
5890                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
5891                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
5892                 // Revoke the old state
5893                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
5894
5895                 {
5896                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5897                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5898                         {
5899                                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5900                                 assert_eq!(node_txn.len(), 3);
5901                                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5902                                 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
5903
5904                                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5905                                 node_txn.swap_remove(0);
5906                         }
5907                         test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
5908
5909                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5910                         let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
5911                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5912                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5913                         test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
5914                 }
5915                 get_announce_close_broadcast_events(&nodes, 0, 1);
5916
5917                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5918                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5919
5920                 // We test justice_tx build by A on B's revoked HTLC-Success tx
5921                 // Create some new channels:
5922                 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
5923
5924                 // A pending HTLC which will be revoked:
5925                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5926                 // Get the will-be-revoked local txn from B
5927                 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5928                 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
5929                 assert_eq!(revoked_local_txn[0].input.len(), 1);
5930                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
5931                 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
5932                 // Revoke the old state
5933                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
5934                 {
5935                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5936                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5937                         {
5938                                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5939                                 assert_eq!(node_txn.len(), 3);
5940                                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5941                                 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
5942
5943                                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5944                                 node_txn.swap_remove(0);
5945                         }
5946                         test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
5947
5948                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5949                         let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
5950                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5951                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5952                         test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone());
5953                 }
5954                 get_announce_close_broadcast_events(&nodes, 0, 1);
5955                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5956                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5957         }
5958
5959         #[test]
5960         fn revoked_output_claim() {
5961                 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
5962                 // transaction is broadcast by its counterparty
5963                 let nodes = create_network(2);
5964                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5965                 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
5966                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5967                 assert_eq!(revoked_local_txn.len(), 1);
5968                 // Only output is the full channel value back to nodes[0]:
5969                 assert_eq!(revoked_local_txn[0].output.len(), 1);
5970                 // Send a payment through, updating everyone's latest commitment txn
5971                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
5972
5973                 // Inform nodes[1] that nodes[0] broadcast a stale tx
5974                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5975                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5976                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5977                 assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
5978
5979                 assert_eq!(node_txn[0], node_txn[2]);
5980
5981                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5982                 check_spends!(node_txn[1], chan_1.3.clone());
5983
5984                 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
5985                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5986                 get_announce_close_broadcast_events(&nodes, 0, 1);
5987         }
5988
5989         #[test]
5990         fn claim_htlc_outputs_shared_tx() {
5991                 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
5992                 let nodes = create_network(2);
5993
5994                 // Create some new channel:
5995                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5996
5997                 // Rebalance the network to generate htlc in the two directions
5998                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5999                 // 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
6000                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6001                 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6002
6003                 // Get the will-be-revoked local txn from node[0]
6004                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6005                 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
6006                 assert_eq!(revoked_local_txn[0].input.len(), 1);
6007                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
6008                 assert_eq!(revoked_local_txn[1].input.len(), 1);
6009                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
6010                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
6011                 check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
6012
6013                 //Revoke the old state
6014                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6015
6016                 {
6017                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6018                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6019                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6020
6021                         let events = nodes[1].node.get_and_clear_pending_events();
6022                         assert_eq!(events.len(), 1);
6023                         match events[0] {
6024                                 Event::PaymentFailed { payment_hash, .. } => {
6025                                         assert_eq!(payment_hash, payment_hash_2);
6026                                 },
6027                                 _ => panic!("Unexpected event"),
6028                         }
6029
6030                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6031                         assert_eq!(node_txn.len(), 4);
6032
6033                         assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
6034                         check_spends!(node_txn[0], revoked_local_txn[0].clone());
6035
6036                         assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
6037
6038                         let mut witness_lens = BTreeSet::new();
6039                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6040                         witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
6041                         witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
6042                         assert_eq!(witness_lens.len(), 3);
6043                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6044                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
6045                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
6046
6047                         // Next nodes[1] broadcasts its current local tx state:
6048                         assert_eq!(node_txn[1].input.len(), 1);
6049                         assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
6050
6051                         assert_eq!(node_txn[2].input.len(), 1);
6052                         let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
6053                         assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
6054                         assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
6055                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6056                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
6057                 }
6058                 get_announce_close_broadcast_events(&nodes, 0, 1);
6059                 assert_eq!(nodes[0].node.list_channels().len(), 0);
6060                 assert_eq!(nodes[1].node.list_channels().len(), 0);
6061         }
6062
6063         #[test]
6064         fn claim_htlc_outputs_single_tx() {
6065                 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
6066                 let nodes = create_network(2);
6067
6068                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6069
6070                 // Rebalance the network to generate htlc in the two directions
6071                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6072                 // 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
6073                 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
6074                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6075                 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6076
6077                 // Get the will-be-revoked local txn from node[0]
6078                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6079
6080                 //Revoke the old state
6081                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6082
6083                 {
6084                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6085                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6086                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6087
6088                         let events = nodes[1].node.get_and_clear_pending_events();
6089                         assert_eq!(events.len(), 1);
6090                         match events[0] {
6091                                 Event::PaymentFailed { payment_hash, .. } => {
6092                                         assert_eq!(payment_hash, payment_hash_2);
6093                                 },
6094                                 _ => panic!("Unexpected event"),
6095                         }
6096
6097                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6098                         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)
6099
6100                         assert_eq!(node_txn[0], node_txn[7]);
6101                         assert_eq!(node_txn[1], node_txn[8]);
6102                         assert_eq!(node_txn[2], node_txn[9]);
6103                         assert_eq!(node_txn[3], node_txn[10]);
6104                         assert_eq!(node_txn[4], node_txn[11]);
6105                         assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcated by ChannelManger
6106                         assert_eq!(node_txn[4], node_txn[6]);
6107
6108                         assert_eq!(node_txn[0].input.len(), 1);
6109                         assert_eq!(node_txn[1].input.len(), 1);
6110                         assert_eq!(node_txn[2].input.len(), 1);
6111
6112                         let mut revoked_tx_map = HashMap::new();
6113                         revoked_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
6114                         node_txn[0].verify(&revoked_tx_map).unwrap();
6115                         node_txn[1].verify(&revoked_tx_map).unwrap();
6116                         node_txn[2].verify(&revoked_tx_map).unwrap();
6117
6118                         let mut witness_lens = BTreeSet::new();
6119                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6120                         witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
6121                         witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
6122                         assert_eq!(witness_lens.len(), 3);
6123                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6124                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
6125                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
6126
6127                         assert_eq!(node_txn[3].input.len(), 1);
6128                         check_spends!(node_txn[3], chan_1.3.clone());
6129
6130                         assert_eq!(node_txn[4].input.len(), 1);
6131                         let witness_script = node_txn[4].input[0].witness.last().unwrap();
6132                         assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
6133                         assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
6134                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6135                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
6136                 }
6137                 get_announce_close_broadcast_events(&nodes, 0, 1);
6138                 assert_eq!(nodes[0].node.list_channels().len(), 0);
6139                 assert_eq!(nodes[1].node.list_channels().len(), 0);
6140         }
6141
6142         #[test]
6143         fn test_htlc_on_chain_success() {
6144                 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
6145                 // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
6146                 // broadcasting the right event to other nodes in payment path.
6147                 // A --------------------> B ----------------------> C (preimage)
6148                 // First, C should claim the HTLC output via HTLC-Success when its own latest local
6149                 // commitment transaction was broadcast.
6150                 // Then, B should learn the preimage from said transactions, attempting to claim backwards
6151                 // towards B.
6152                 // B should be able to claim via preimage if A then broadcasts its local tx.
6153                 // Finally, when A sees B's latest local commitment transaction it should be able to claim
6154                 // the HTLC output via the preimage it learned (which, once confirmed should generate a
6155                 // PaymentSent event).
6156
6157                 let nodes = create_network(3);
6158
6159                 // Create some initial channels
6160                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6161                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6162
6163                 // Rebalance the network a bit by relaying one payment through all the channels...
6164                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6165                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6166
6167                 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
6168                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6169
6170                 // Broadcast legit commitment tx from C on B's chain
6171                 // Broadcast HTLC Success transation by C on received output from C's commitment tx on B's chain
6172                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6173                 assert_eq!(commitment_tx.len(), 1);
6174                 check_spends!(commitment_tx[0], chan_2.3.clone());
6175                 nodes[2].node.claim_funds(our_payment_preimage);
6176                 check_added_monitors!(nodes[2], 1);
6177                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6178                 assert!(updates.update_add_htlcs.is_empty());
6179                 assert!(updates.update_fail_htlcs.is_empty());
6180                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6181                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
6182
6183                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6184                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6185                 assert_eq!(events.len(), 1);
6186                 match events[0] {
6187                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6188                         _ => panic!("Unexpected event"),
6189                 }
6190                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
6191                 assert_eq!(node_txn.len(), 3);
6192                 assert_eq!(node_txn[1], commitment_tx[0]);
6193                 assert_eq!(node_txn[0], node_txn[2]);
6194                 check_spends!(node_txn[0], commitment_tx[0].clone());
6195                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6196                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6197                 assert_eq!(node_txn[0].lock_time, 0);
6198
6199                 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
6200                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: node_txn}, 1);
6201                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6202                 {
6203                         let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
6204                         assert_eq!(added_monitors.len(), 1);
6205                         assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
6206                         added_monitors.clear();
6207                 }
6208                 assert_eq!(events.len(), 2);
6209                 match events[0] {
6210                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6211                         _ => panic!("Unexpected event"),
6212                 }
6213                 match events[1] {
6214                         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, .. } } => {
6215                                 assert!(update_add_htlcs.is_empty());
6216                                 assert!(update_fail_htlcs.is_empty());
6217                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6218                                 assert!(update_fail_malformed_htlcs.is_empty());
6219                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6220                         },
6221                         _ => panic!("Unexpected event"),
6222                 };
6223                 {
6224                         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
6225                         // commitment transaction with a corresponding HTLC-Timeout transaction, as well as a
6226                         // timeout-claim of the output that nodes[2] just claimed via success.
6227                         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)
6228                         assert_eq!(node_txn.len(), 4);
6229                         assert_eq!(node_txn[0], node_txn[3]);
6230                         check_spends!(node_txn[0], commitment_tx[0].clone());
6231                         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6232                         assert_ne!(node_txn[0].lock_time, 0);
6233                         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
6234                         check_spends!(node_txn[1], chan_2.3.clone());
6235                         check_spends!(node_txn[2], node_txn[1].clone());
6236                         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6237                         assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6238                         assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6239                         assert_ne!(node_txn[2].lock_time, 0);
6240                         node_txn.clear();
6241                 }
6242
6243                 // Broadcast legit commitment tx from A on B's chain
6244                 // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
6245                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6246                 check_spends!(commitment_tx[0], chan_1.3.clone());
6247                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6248                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6249                 assert_eq!(events.len(), 1);
6250                 match events[0] {
6251                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6252                         _ => panic!("Unexpected event"),
6253                 }
6254                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 1 (HTLC-Success) * 2 (block-rescan)
6255                 assert_eq!(node_txn.len(), 3);
6256                 assert_eq!(node_txn[0], node_txn[2]);
6257                 check_spends!(node_txn[0], commitment_tx[0].clone());
6258                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6259                 assert_eq!(node_txn[0].lock_time, 0);
6260                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
6261                 check_spends!(node_txn[1], chan_1.3.clone());
6262                 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6263                 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
6264                 // we already checked the same situation with A.
6265
6266                 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
6267                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
6268                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6269                 assert_eq!(events.len(), 1);
6270                 match events[0] {
6271                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6272                         _ => panic!("Unexpected event"),
6273                 }
6274                 let events = nodes[0].node.get_and_clear_pending_events();
6275                 assert_eq!(events.len(), 1);
6276                 match events[0] {
6277                         Event::PaymentSent { payment_preimage } => {
6278                                 assert_eq!(payment_preimage, our_payment_preimage);
6279                         },
6280                         _ => panic!("Unexpected event"),
6281                 }
6282                 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)
6283                 assert_eq!(node_txn.len(), 4);
6284                 assert_eq!(node_txn[0], node_txn[3]);
6285                 check_spends!(node_txn[0], commitment_tx[0].clone());
6286                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6287                 assert_ne!(node_txn[0].lock_time, 0);
6288                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6289                 check_spends!(node_txn[1], chan_1.3.clone());
6290                 check_spends!(node_txn[2], node_txn[1].clone());
6291                 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6292                 assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6293                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6294                 assert_ne!(node_txn[2].lock_time, 0);
6295         }
6296
6297         #[test]
6298         fn test_htlc_on_chain_timeout() {
6299                 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
6300                 // ChainWatchInterface and timeout the HTLC  bacward accordingly. So here we test that ChannelManager is
6301                 // broadcasting the right event to other nodes in payment path.
6302                 // A ------------------> B ----------------------> C (timeout)
6303                 //    B's commitment tx                 C's commitment tx
6304                 //            \                                  \
6305                 //         B's HTLC timeout tx               B's timeout tx
6306
6307                 let nodes = create_network(3);
6308
6309                 // Create some intial channels
6310                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6311                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6312
6313                 // Rebalance the network a bit by relaying one payment thorugh all the channels...
6314                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6315                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6316
6317                 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
6318                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6319
6320                 // Brodacast legit commitment tx from C on B's chain
6321                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6322                 check_spends!(commitment_tx[0], chan_2.3.clone());
6323                 nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
6324                 {
6325                         let mut added_monitors = nodes[2].chan_monitor.added_monitors.lock().unwrap();
6326                         assert_eq!(added_monitors.len(), 1);
6327                         added_monitors.clear();
6328                 }
6329                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6330                 assert_eq!(events.len(), 1);
6331                 match events[0] {
6332                         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, .. } } => {
6333                                 assert!(update_add_htlcs.is_empty());
6334                                 assert!(!update_fail_htlcs.is_empty());
6335                                 assert!(update_fulfill_htlcs.is_empty());
6336                                 assert!(update_fail_malformed_htlcs.is_empty());
6337                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
6338                         },
6339                         _ => panic!("Unexpected event"),
6340                 };
6341                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6342                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6343                 assert_eq!(events.len(), 1);
6344                 match events[0] {
6345                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6346                         _ => panic!("Unexpected event"),
6347                 }
6348                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
6349                 assert_eq!(node_txn.len(), 1);
6350                 check_spends!(node_txn[0], chan_2.3.clone());
6351                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
6352
6353                 // Broadcast timeout transaction by B on received output fron C's commitment tx on B's chain
6354                 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
6355                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6356                 let timeout_tx;
6357                 {
6358                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6359                         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)
6360                         assert_eq!(node_txn[0], node_txn[5]);
6361                         assert_eq!(node_txn[1], node_txn[6]);
6362                         assert_eq!(node_txn[2], node_txn[7]);
6363                         check_spends!(node_txn[0], commitment_tx[0].clone());
6364                         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6365                         check_spends!(node_txn[1], chan_2.3.clone());
6366                         check_spends!(node_txn[2], node_txn[1].clone());
6367                         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6368                         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6369                         check_spends!(node_txn[3], chan_2.3.clone());
6370                         check_spends!(node_txn[4], node_txn[3].clone());
6371                         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
6372                         assert_eq!(node_txn[4].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6373                         timeout_tx = node_txn[0].clone();
6374                         node_txn.clear();
6375                 }
6376
6377                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![timeout_tx]}, 1);
6378                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6379                 check_added_monitors!(nodes[1], 1);
6380                 assert_eq!(events.len(), 2);
6381                 match events[0] {
6382                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6383                         _ => panic!("Unexpected event"),
6384                 }
6385                 match events[1] {
6386                         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, .. } } => {
6387                                 assert!(update_add_htlcs.is_empty());
6388                                 assert!(!update_fail_htlcs.is_empty());
6389                                 assert!(update_fulfill_htlcs.is_empty());
6390                                 assert!(update_fail_malformed_htlcs.is_empty());
6391                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6392                         },
6393                         _ => panic!("Unexpected event"),
6394                 };
6395                 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
6396                 assert_eq!(node_txn.len(), 0);
6397
6398                 // Broadcast legit commitment tx from B on A's chain
6399                 let commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6400                 check_spends!(commitment_tx[0], chan_1.3.clone());
6401
6402                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6403                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6404                 assert_eq!(events.len(), 1);
6405                 match events[0] {
6406                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6407                         _ => panic!("Unexpected event"),
6408                 }
6409                 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
6410                 assert_eq!(node_txn.len(), 4);
6411                 assert_eq!(node_txn[0], node_txn[3]);
6412                 check_spends!(node_txn[0], commitment_tx[0].clone());
6413                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6414                 check_spends!(node_txn[1], chan_1.3.clone());
6415                 check_spends!(node_txn[2], node_txn[1].clone());
6416                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6417                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6418         }
6419
6420         #[test]
6421         fn test_simple_commitment_revoked_fail_backward() {
6422                 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
6423                 // and fail backward accordingly.
6424
6425                 let nodes = create_network(3);
6426
6427                 // Create some initial channels
6428                 create_announced_chan_between_nodes(&nodes, 0, 1);
6429                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6430
6431                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6432                 // Get the will-be-revoked local txn from nodes[2]
6433                 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6434                 // Revoke the old state
6435                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6436
6437                 route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6438
6439                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6440                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6441                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6442                 check_added_monitors!(nodes[1], 1);
6443                 assert_eq!(events.len(), 2);
6444                 match events[0] {
6445                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6446                         _ => panic!("Unexpected event"),
6447                 }
6448                 match events[1] {
6449                         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, .. } } => {
6450                                 assert!(update_add_htlcs.is_empty());
6451                                 assert_eq!(update_fail_htlcs.len(), 1);
6452                                 assert!(update_fulfill_htlcs.is_empty());
6453                                 assert!(update_fail_malformed_htlcs.is_empty());
6454                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6455
6456                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6457                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6458
6459                                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6460                                 assert_eq!(events.len(), 1);
6461                                 match events[0] {
6462                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6463                                         _ => panic!("Unexpected event"),
6464                                 }
6465                                 let events = nodes[0].node.get_and_clear_pending_events();
6466                                 assert_eq!(events.len(), 1);
6467                                 match events[0] {
6468                                         Event::PaymentFailed { .. } => {},
6469                                         _ => panic!("Unexpected event"),
6470                                 }
6471                         },
6472                         _ => panic!("Unexpected event"),
6473                 }
6474         }
6475
6476         fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool) {
6477                 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
6478                 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
6479                 // commitment transaction anymore.
6480                 // To do this, we have the peer which will broadcast a revoked commitment transaction send
6481                 // a number of update_fail/commitment_signed updates without ever sending the RAA in
6482                 // response to our commitment_signed. This is somewhat misbehavior-y, though not
6483                 // technically disallowed and we should probably handle it reasonably.
6484                 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
6485                 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
6486                 // transactions:
6487                 // * Once we move it out of our holding cell/add it, we will immediately include it in a
6488                 //   commitment_signed (implying it will be in the latest remote commitment transaction).
6489                 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
6490                 //   and once they revoke the previous commitment transaction (allowing us to send a new
6491                 //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
6492                 let mut nodes = create_network(3);
6493
6494                 // Create some initial channels
6495                 create_announced_chan_between_nodes(&nodes, 0, 1);
6496                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6497
6498                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6499                 // Get the will-be-revoked local txn from nodes[2]
6500                 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6501                 // Revoke the old state
6502                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6503
6504                 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6505                 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6506                 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6507
6508                 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, 0));
6509                 check_added_monitors!(nodes[2], 1);
6510                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6511                 assert!(updates.update_add_htlcs.is_empty());
6512                 assert!(updates.update_fulfill_htlcs.is_empty());
6513                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6514                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6515                 assert!(updates.update_fee.is_none());
6516                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6517                 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
6518                 // Drop the last RAA from 3 -> 2
6519
6520                 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, 0));
6521                 check_added_monitors!(nodes[2], 1);
6522                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6523                 assert!(updates.update_add_htlcs.is_empty());
6524                 assert!(updates.update_fulfill_htlcs.is_empty());
6525                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6526                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6527                 assert!(updates.update_fee.is_none());
6528                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6529                 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6530                 check_added_monitors!(nodes[1], 1);
6531                 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
6532                 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6533                 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6534                 check_added_monitors!(nodes[2], 1);
6535
6536                 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, 0));
6537                 check_added_monitors!(nodes[2], 1);
6538                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6539                 assert!(updates.update_add_htlcs.is_empty());
6540                 assert!(updates.update_fulfill_htlcs.is_empty());
6541                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6542                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6543                 assert!(updates.update_fee.is_none());
6544                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6545                 // At this point first_payment_hash has dropped out of the latest two commitment
6546                 // transactions that nodes[1] is tracking...
6547                 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6548                 check_added_monitors!(nodes[1], 1);
6549                 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
6550                 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6551                 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6552                 check_added_monitors!(nodes[2], 1);
6553
6554                 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
6555                 // on nodes[2]'s RAA.
6556                 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
6557                 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6558                 nodes[1].node.send_payment(route, fourth_payment_hash).unwrap();
6559                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
6560                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6561                 check_added_monitors!(nodes[1], 0);
6562
6563                 if deliver_bs_raa {
6564                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa).unwrap();
6565                         // One monitor for the new revocation preimage, one as we generate a commitment for
6566                         // nodes[0] to fail first_payment_hash backwards.
6567                         check_added_monitors!(nodes[1], 2);
6568                 }
6569
6570                 let mut failed_htlcs = HashSet::new();
6571                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6572
6573                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6574                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6575
6576                 let events = nodes[1].node.get_and_clear_pending_events();
6577                 assert_eq!(events.len(), 1);
6578                 match events[0] {
6579                         Event::PaymentFailed { ref payment_hash, .. } => {
6580                                 assert_eq!(*payment_hash, fourth_payment_hash);
6581                         },
6582                         _ => panic!("Unexpected event"),
6583                 }
6584
6585                 if !deliver_bs_raa {
6586                         // If we delivered the RAA already then we already failed first_payment_hash backwards.
6587                         check_added_monitors!(nodes[1], 1);
6588                 }
6589
6590                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6591                 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
6592                 match events[if deliver_bs_raa { 2 } else { 0 }] {
6593                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6594                         _ => panic!("Unexpected event"),
6595                 }
6596                 if deliver_bs_raa {
6597                         match events[0] {
6598                                 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, .. } } => {
6599                                         assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
6600                                         assert_eq!(update_add_htlcs.len(), 1);
6601                                         assert!(update_fulfill_htlcs.is_empty());
6602                                         assert!(update_fail_htlcs.is_empty());
6603                                         assert!(update_fail_malformed_htlcs.is_empty());
6604                                 },
6605                                 _ => panic!("Unexpected event"),
6606                         }
6607                 }
6608                 // Due to the way backwards-failing occurs we do the updates in two steps.
6609                 let updates = match events[1] {
6610                         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, .. } } => {
6611                                 assert!(update_add_htlcs.is_empty());
6612                                 assert_eq!(update_fail_htlcs.len(), 1);
6613                                 assert!(update_fulfill_htlcs.is_empty());
6614                                 assert!(update_fail_malformed_htlcs.is_empty());
6615                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6616
6617                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6618                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
6619                                 check_added_monitors!(nodes[0], 1);
6620                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6621                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6622                                 check_added_monitors!(nodes[1], 1);
6623                                 let bs_second_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6624                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
6625                                 check_added_monitors!(nodes[1], 1);
6626                                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6627                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6628                                 check_added_monitors!(nodes[0], 1);
6629
6630                                 if !deliver_bs_raa {
6631                                         // If we delievered B's RAA we got an unknown preimage error, not something
6632                                         // that we should update our routing table for.
6633                                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6634                                         assert_eq!(events.len(), 1);
6635                                         match events[0] {
6636                                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6637                                                 _ => panic!("Unexpected event"),
6638                                         }
6639                                 }
6640                                 let events = nodes[0].node.get_and_clear_pending_events();
6641                                 assert_eq!(events.len(), 1);
6642                                 match events[0] {
6643                                         Event::PaymentFailed { ref payment_hash, .. } => {
6644                                                 assert!(failed_htlcs.insert(payment_hash.0));
6645                                         },
6646                                         _ => panic!("Unexpected event"),
6647                                 }
6648
6649                                 bs_second_update
6650                         },
6651                         _ => panic!("Unexpected event"),
6652                 };
6653
6654                 assert!(updates.update_add_htlcs.is_empty());
6655                 assert_eq!(updates.update_fail_htlcs.len(), 2);
6656                 assert!(updates.update_fulfill_htlcs.is_empty());
6657                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6658                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6659                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[1]).unwrap();
6660                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6661
6662                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6663                 assert_eq!(events.len(), 2);
6664                 for event in events {
6665                         match event {
6666                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6667                                 _ => panic!("Unexpected event"),
6668                         }
6669                 }
6670
6671                 let events = nodes[0].node.get_and_clear_pending_events();
6672                 assert_eq!(events.len(), 2);
6673                 match events[0] {
6674                         Event::PaymentFailed { ref payment_hash, .. } => {
6675                                 assert!(failed_htlcs.insert(payment_hash.0));
6676                         },
6677                         _ => panic!("Unexpected event"),
6678                 }
6679                 match events[1] {
6680                         Event::PaymentFailed { ref payment_hash, .. } => {
6681                                 assert!(failed_htlcs.insert(payment_hash.0));
6682                         },
6683                         _ => panic!("Unexpected event"),
6684                 }
6685
6686                 assert!(failed_htlcs.contains(&first_payment_hash.0));
6687                 assert!(failed_htlcs.contains(&second_payment_hash.0));
6688                 assert!(failed_htlcs.contains(&third_payment_hash.0));
6689         }
6690
6691         #[test]
6692         fn test_commitment_revoked_fail_backward_exhaustive() {
6693                 do_test_commitment_revoked_fail_backward_exhaustive(false);
6694                 do_test_commitment_revoked_fail_backward_exhaustive(true);
6695         }
6696
6697         #[test]
6698         fn test_htlc_ignore_latest_remote_commitment() {
6699                 // Test that HTLC transactions spending the latest remote commitment transaction are simply
6700                 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
6701                 let nodes = create_network(2);
6702                 create_announced_chan_between_nodes(&nodes, 0, 1);
6703
6704                 route_payment(&nodes[0], &[&nodes[1]], 10000000);
6705                 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
6706                 {
6707                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6708                         assert_eq!(events.len(), 1);
6709                         match events[0] {
6710                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6711                                         assert_eq!(flags & 0b10, 0b10);
6712                                 },
6713                                 _ => panic!("Unexpected event"),
6714                         }
6715                 }
6716
6717                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6718                 assert_eq!(node_txn.len(), 2);
6719
6720                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6721                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6722
6723                 {
6724                         let events = nodes[1].node.get_and_clear_pending_msg_events();
6725                         assert_eq!(events.len(), 1);
6726                         match events[0] {
6727                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6728                                         assert_eq!(flags & 0b10, 0b10);
6729                                 },
6730                                 _ => panic!("Unexpected event"),
6731                         }
6732                 }
6733
6734                 // Duplicate the block_connected call since this may happen due to other listeners
6735                 // registering new transactions
6736                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6737         }
6738
6739         #[test]
6740         fn test_force_close_fail_back() {
6741                 // Check which HTLCs are failed-backwards on channel force-closure
6742                 let mut nodes = create_network(3);
6743                 create_announced_chan_between_nodes(&nodes, 0, 1);
6744                 create_announced_chan_between_nodes(&nodes, 1, 2);
6745
6746                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
6747
6748                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6749
6750                 let mut payment_event = {
6751                         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6752                         check_added_monitors!(nodes[0], 1);
6753
6754                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6755                         assert_eq!(events.len(), 1);
6756                         SendEvent::from_event(events.remove(0))
6757                 };
6758
6759                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6760                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6761
6762                 let events_1 = nodes[1].node.get_and_clear_pending_events();
6763                 assert_eq!(events_1.len(), 1);
6764                 match events_1[0] {
6765                         Event::PendingHTLCsForwardable { .. } => { },
6766                         _ => panic!("Unexpected event"),
6767                 };
6768
6769                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
6770                 nodes[1].node.process_pending_htlc_forwards();
6771
6772                 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6773                 assert_eq!(events_2.len(), 1);
6774                 payment_event = SendEvent::from_event(events_2.remove(0));
6775                 assert_eq!(payment_event.msgs.len(), 1);
6776
6777                 check_added_monitors!(nodes[1], 1);
6778                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6779                 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
6780                 check_added_monitors!(nodes[2], 1);
6781                 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6782
6783                 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
6784                 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
6785                 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
6786
6787                 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
6788                 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6789                 assert_eq!(events_3.len(), 1);
6790                 match events_3[0] {
6791                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6792                                 assert_eq!(flags & 0b10, 0b10);
6793                         },
6794                         _ => panic!("Unexpected event"),
6795                 }
6796
6797                 let tx = {
6798                         let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6799                         // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
6800                         // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
6801                         // back to nodes[1] upon timeout otherwise.
6802                         assert_eq!(node_txn.len(), 1);
6803                         node_txn.remove(0)
6804                 };
6805
6806                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6807                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6808
6809                 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6810                 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
6811                 assert_eq!(events_4.len(), 1);
6812                 match events_4[0] {
6813                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6814                                 assert_eq!(flags & 0b10, 0b10);
6815                         },
6816                         _ => panic!("Unexpected event"),
6817                 }
6818
6819                 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
6820                 {
6821                         let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
6822                         monitors.get_mut(&OutPoint::new(Sha256dHash::from(&payment_event.commitment_msg.channel_id[..]), 0)).unwrap()
6823                                 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
6824                 }
6825                 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6826                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6827                 assert_eq!(node_txn.len(), 1);
6828                 assert_eq!(node_txn[0].input.len(), 1);
6829                 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
6830                 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
6831                 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
6832
6833                 check_spends!(node_txn[0], tx);
6834         }
6835
6836         #[test]
6837         fn test_unconf_chan() {
6838                 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
6839                 let nodes = create_network(2);
6840                 create_announced_chan_between_nodes(&nodes, 0, 1);
6841
6842                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6843                 assert_eq!(channel_state.by_id.len(), 1);
6844                 assert_eq!(channel_state.short_to_id.len(), 1);
6845                 mem::drop(channel_state);
6846
6847                 let mut headers = Vec::new();
6848                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6849                 headers.push(header.clone());
6850                 for _i in 2..100 {
6851                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6852                         headers.push(header.clone());
6853                 }
6854                 while !headers.is_empty() {
6855                         nodes[0].node.block_disconnected(&headers.pop().unwrap());
6856                 }
6857                 {
6858                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6859                         assert_eq!(events.len(), 1);
6860                         match events[0] {
6861                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6862                                         assert_eq!(flags & 0b10, 0b10);
6863                                 },
6864                                 _ => panic!("Unexpected event"),
6865                         }
6866                 }
6867                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6868                 assert_eq!(channel_state.by_id.len(), 0);
6869                 assert_eq!(channel_state.short_to_id.len(), 0);
6870         }
6871
6872         macro_rules! get_chan_reestablish_msgs {
6873                 ($src_node: expr, $dst_node: expr) => {
6874                         {
6875                                 let mut res = Vec::with_capacity(1);
6876                                 for msg in $src_node.node.get_and_clear_pending_msg_events() {
6877                                         if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
6878                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6879                                                 res.push(msg.clone());
6880                                         } else {
6881                                                 panic!("Unexpected event")
6882                                         }
6883                                 }
6884                                 res
6885                         }
6886                 }
6887         }
6888
6889         macro_rules! handle_chan_reestablish_msgs {
6890                 ($src_node: expr, $dst_node: expr) => {
6891                         {
6892                                 let msg_events = $src_node.node.get_and_clear_pending_msg_events();
6893                                 let mut idx = 0;
6894                                 let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
6895                                         idx += 1;
6896                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6897                                         Some(msg.clone())
6898                                 } else {
6899                                         None
6900                                 };
6901
6902                                 let mut revoke_and_ack = None;
6903                                 let mut commitment_update = None;
6904                                 let order = if let Some(ev) = msg_events.get(idx) {
6905                                         idx += 1;
6906                                         match ev {
6907                                                 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6908                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6909                                                         revoke_and_ack = Some(msg.clone());
6910                                                         RAACommitmentOrder::RevokeAndACKFirst
6911                                                 },
6912                                                 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6913                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6914                                                         commitment_update = Some(updates.clone());
6915                                                         RAACommitmentOrder::CommitmentFirst
6916                                                 },
6917                                                 _ => panic!("Unexpected event"),
6918                                         }
6919                                 } else {
6920                                         RAACommitmentOrder::CommitmentFirst
6921                                 };
6922
6923                                 if let Some(ev) = msg_events.get(idx) {
6924                                         match ev {
6925                                                 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6926                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6927                                                         assert!(revoke_and_ack.is_none());
6928                                                         revoke_and_ack = Some(msg.clone());
6929                                                 },
6930                                                 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6931                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6932                                                         assert!(commitment_update.is_none());
6933                                                         commitment_update = Some(updates.clone());
6934                                                 },
6935                                                 _ => panic!("Unexpected event"),
6936                                         }
6937                                 }
6938
6939                                 (funding_locked, revoke_and_ack, commitment_update, order)
6940                         }
6941                 }
6942         }
6943
6944         /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
6945         /// for claims/fails they are separated out.
6946         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)) {
6947                 node_a.node.peer_connected(&node_b.node.get_our_node_id());
6948                 let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
6949                 node_b.node.peer_connected(&node_a.node.get_our_node_id());
6950                 let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
6951
6952                 if send_funding_locked.0 {
6953                         // If a expects a funding_locked, it better not think it has received a revoke_and_ack
6954                         // from b
6955                         for reestablish in reestablish_1.iter() {
6956                                 assert_eq!(reestablish.next_remote_commitment_number, 0);
6957                         }
6958                 }
6959                 if send_funding_locked.1 {
6960                         // If b expects a funding_locked, it better not think it has received a revoke_and_ack
6961                         // from a
6962                         for reestablish in reestablish_2.iter() {
6963                                 assert_eq!(reestablish.next_remote_commitment_number, 0);
6964                         }
6965                 }
6966                 if send_funding_locked.0 || send_funding_locked.1 {
6967                         // If we expect any funding_locked's, both sides better have set
6968                         // next_local_commitment_number to 1
6969                         for reestablish in reestablish_1.iter() {
6970                                 assert_eq!(reestablish.next_local_commitment_number, 1);
6971                         }
6972                         for reestablish in reestablish_2.iter() {
6973                                 assert_eq!(reestablish.next_local_commitment_number, 1);
6974                         }
6975                 }
6976
6977                 let mut resp_1 = Vec::new();
6978                 for msg in reestablish_1 {
6979                         node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg).unwrap();
6980                         resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
6981                 }
6982                 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
6983                         check_added_monitors!(node_b, 1);
6984                 } else {
6985                         check_added_monitors!(node_b, 0);
6986                 }
6987
6988                 let mut resp_2 = Vec::new();
6989                 for msg in reestablish_2 {
6990                         node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg).unwrap();
6991                         resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
6992                 }
6993                 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
6994                         check_added_monitors!(node_a, 1);
6995                 } else {
6996                         check_added_monitors!(node_a, 0);
6997                 }
6998
6999                 // We dont yet support both needing updates, as that would require a different commitment dance:
7000                 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
7001                         (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
7002
7003                 for chan_msgs in resp_1.drain(..) {
7004                         if send_funding_locked.0 {
7005                                 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
7006                                 let announcement_event = node_a.node.get_and_clear_pending_msg_events();
7007                                 if !announcement_event.is_empty() {
7008                                         assert_eq!(announcement_event.len(), 1);
7009                                         if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
7010                                                 //TODO: Test announcement_sigs re-sending
7011                                         } else { panic!("Unexpected event!"); }
7012                                 }
7013                         } else {
7014                                 assert!(chan_msgs.0.is_none());
7015                         }
7016                         if pending_raa.0 {
7017                                 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
7018                                 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
7019                                 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
7020                                 check_added_monitors!(node_a, 1);
7021                         } else {
7022                                 assert!(chan_msgs.1.is_none());
7023                         }
7024                         if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
7025                                 let commitment_update = chan_msgs.2.unwrap();
7026                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
7027                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
7028                                 } else {
7029                                         assert!(commitment_update.update_add_htlcs.is_empty());
7030                                 }
7031                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
7032                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
7033                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
7034                                 for update_add in commitment_update.update_add_htlcs {
7035                                         node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add).unwrap();
7036                                 }
7037                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
7038                                         node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill).unwrap();
7039                                 }
7040                                 for update_fail in commitment_update.update_fail_htlcs {
7041                                         node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail).unwrap();
7042                                 }
7043
7044                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
7045                                         commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
7046                                 } else {
7047                                         node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
7048                                         check_added_monitors!(node_a, 1);
7049                                         let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
7050                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
7051                                         node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7052                                         assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
7053                                         check_added_monitors!(node_b, 1);
7054                                 }
7055                         } else {
7056                                 assert!(chan_msgs.2.is_none());
7057                         }
7058                 }
7059
7060                 for chan_msgs in resp_2.drain(..) {
7061                         if send_funding_locked.1 {
7062                                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
7063                                 let announcement_event = node_b.node.get_and_clear_pending_msg_events();
7064                                 if !announcement_event.is_empty() {
7065                                         assert_eq!(announcement_event.len(), 1);
7066                                         if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
7067                                                 //TODO: Test announcement_sigs re-sending
7068                                         } else { panic!("Unexpected event!"); }
7069                                 }
7070                         } else {
7071                                 assert!(chan_msgs.0.is_none());
7072                         }
7073                         if pending_raa.1 {
7074                                 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
7075                                 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
7076                                 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
7077                                 check_added_monitors!(node_b, 1);
7078                         } else {
7079                                 assert!(chan_msgs.1.is_none());
7080                         }
7081                         if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
7082                                 let commitment_update = chan_msgs.2.unwrap();
7083                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
7084                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
7085                                 }
7086                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
7087                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
7088                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
7089                                 for update_add in commitment_update.update_add_htlcs {
7090                                         node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add).unwrap();
7091                                 }
7092                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
7093                                         node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill).unwrap();
7094                                 }
7095                                 for update_fail in commitment_update.update_fail_htlcs {
7096                                         node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail).unwrap();
7097                                 }
7098
7099                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
7100                                         commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
7101                                 } else {
7102                                         node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
7103                                         check_added_monitors!(node_b, 1);
7104                                         let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
7105                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
7106                                         node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7107                                         assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
7108                                         check_added_monitors!(node_a, 1);
7109                                 }
7110                         } else {
7111                                 assert!(chan_msgs.2.is_none());
7112                         }
7113                 }
7114         }
7115
7116         #[test]
7117         fn test_simple_peer_disconnect() {
7118                 // Test that we can reconnect when there are no lost messages
7119                 let nodes = create_network(3);
7120                 create_announced_chan_between_nodes(&nodes, 0, 1);
7121                 create_announced_chan_between_nodes(&nodes, 1, 2);
7122
7123                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7124                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7125                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7126
7127                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7128                 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7129                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
7130                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
7131
7132                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7133                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7134                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7135
7136                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7137                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7138                 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7139                 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7140
7141                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7142                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7143
7144                 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3);
7145                 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
7146
7147                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
7148                 {
7149                         let events = nodes[0].node.get_and_clear_pending_events();
7150                         assert_eq!(events.len(), 2);
7151                         match events[0] {
7152                                 Event::PaymentSent { payment_preimage } => {
7153                                         assert_eq!(payment_preimage, payment_preimage_3);
7154                                 },
7155                                 _ => panic!("Unexpected event"),
7156                         }
7157                         match events[1] {
7158                                 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
7159                                         assert_eq!(payment_hash, payment_hash_5);
7160                                         assert!(rejected_by_dest);
7161                                 },
7162                                 _ => panic!("Unexpected event"),
7163                         }
7164                 }
7165
7166                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
7167                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
7168         }
7169
7170         fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
7171                 // Test that we can reconnect when in-flight HTLC updates get dropped
7172                 let mut nodes = create_network(2);
7173                 if messages_delivered == 0 {
7174                         create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
7175                         // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
7176                 } else {
7177                         create_announced_chan_between_nodes(&nodes, 0, 1);
7178                 }
7179
7180                 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();
7181                 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7182
7183                 let payment_event = {
7184                         nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
7185                         check_added_monitors!(nodes[0], 1);
7186
7187                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7188                         assert_eq!(events.len(), 1);
7189                         SendEvent::from_event(events.remove(0))
7190                 };
7191                 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
7192
7193                 if messages_delivered < 2 {
7194                         // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
7195                 } else {
7196                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7197                         if messages_delivered >= 3 {
7198                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7199                                 check_added_monitors!(nodes[1], 1);
7200                                 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7201
7202                                 if messages_delivered >= 4 {
7203                                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7204                                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7205                                         check_added_monitors!(nodes[0], 1);
7206
7207                                         if messages_delivered >= 5 {
7208                                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
7209                                                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7210                                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7211                                                 check_added_monitors!(nodes[0], 1);
7212
7213                                                 if messages_delivered >= 6 {
7214                                                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7215                                                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7216                                                         check_added_monitors!(nodes[1], 1);
7217                                                 }
7218                                         }
7219                                 }
7220                         }
7221                 }
7222
7223                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7224                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7225                 if messages_delivered < 3 {
7226                         // Even if the funding_locked messages get exchanged, as long as nothing further was
7227                         // received on either side, both sides will need to resend them.
7228                         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
7229                 } else if messages_delivered == 3 {
7230                         // nodes[0] still wants its RAA + commitment_signed
7231                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
7232                 } else if messages_delivered == 4 {
7233                         // nodes[0] still wants its commitment_signed
7234                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
7235                 } else if messages_delivered == 5 {
7236                         // nodes[1] still wants its final RAA
7237                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
7238                 } else if messages_delivered == 6 {
7239                         // Everything was delivered...
7240                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7241                 }
7242
7243                 let events_1 = nodes[1].node.get_and_clear_pending_events();
7244                 assert_eq!(events_1.len(), 1);
7245                 match events_1[0] {
7246                         Event::PendingHTLCsForwardable { .. } => { },
7247                         _ => panic!("Unexpected event"),
7248                 };
7249
7250                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7251                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7252                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7253
7254                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7255                 nodes[1].node.process_pending_htlc_forwards();
7256
7257                 let events_2 = nodes[1].node.get_and_clear_pending_events();
7258                 assert_eq!(events_2.len(), 1);
7259                 match events_2[0] {
7260                         Event::PaymentReceived { ref payment_hash, amt } => {
7261                                 assert_eq!(payment_hash_1, *payment_hash);
7262                                 assert_eq!(amt, 1000000);
7263                         },
7264                         _ => panic!("Unexpected event"),
7265                 }
7266
7267                 nodes[1].node.claim_funds(payment_preimage_1);
7268                 check_added_monitors!(nodes[1], 1);
7269
7270                 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
7271                 assert_eq!(events_3.len(), 1);
7272                 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
7273                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
7274                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7275                                 assert!(updates.update_add_htlcs.is_empty());
7276                                 assert!(updates.update_fail_htlcs.is_empty());
7277                                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
7278                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
7279                                 assert!(updates.update_fee.is_none());
7280                                 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
7281                         },
7282                         _ => panic!("Unexpected event"),
7283                 };
7284
7285                 if messages_delivered >= 1 {
7286                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc).unwrap();
7287
7288                         let events_4 = nodes[0].node.get_and_clear_pending_events();
7289                         assert_eq!(events_4.len(), 1);
7290                         match events_4[0] {
7291                                 Event::PaymentSent { ref payment_preimage } => {
7292                                         assert_eq!(payment_preimage_1, *payment_preimage);
7293                                 },
7294                                 _ => panic!("Unexpected event"),
7295                         }
7296
7297                         if messages_delivered >= 2 {
7298                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
7299                                 check_added_monitors!(nodes[0], 1);
7300                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7301
7302                                 if messages_delivered >= 3 {
7303                                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7304                                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7305                                         check_added_monitors!(nodes[1], 1);
7306
7307                                         if messages_delivered >= 4 {
7308                                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
7309                                                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7310                                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7311                                                 check_added_monitors!(nodes[1], 1);
7312
7313                                                 if messages_delivered >= 5 {
7314                                                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7315                                                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7316                                                         check_added_monitors!(nodes[0], 1);
7317                                                 }
7318                                         }
7319                                 }
7320                         }
7321                 }
7322
7323                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7324                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7325                 if messages_delivered < 2 {
7326                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
7327                         //TODO: Deduplicate PaymentSent events, then enable this if:
7328                         //if messages_delivered < 1 {
7329                                 let events_4 = nodes[0].node.get_and_clear_pending_events();
7330                                 assert_eq!(events_4.len(), 1);
7331                                 match events_4[0] {
7332                                         Event::PaymentSent { ref payment_preimage } => {
7333                                                 assert_eq!(payment_preimage_1, *payment_preimage);
7334                                         },
7335                                         _ => panic!("Unexpected event"),
7336                                 }
7337                         //}
7338                 } else if messages_delivered == 2 {
7339                         // nodes[0] still wants its RAA + commitment_signed
7340                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
7341                 } else if messages_delivered == 3 {
7342                         // nodes[0] still wants its commitment_signed
7343                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
7344                 } else if messages_delivered == 4 {
7345                         // nodes[1] still wants its final RAA
7346                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
7347                 } else if messages_delivered == 5 {
7348                         // Everything was delivered...
7349                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7350                 }
7351
7352                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7353                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7354                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7355
7356                 // Channel should still work fine...
7357                 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
7358                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7359         }
7360
7361         #[test]
7362         fn test_drop_messages_peer_disconnect_a() {
7363                 do_test_drop_messages_peer_disconnect(0);
7364                 do_test_drop_messages_peer_disconnect(1);
7365                 do_test_drop_messages_peer_disconnect(2);
7366                 do_test_drop_messages_peer_disconnect(3);
7367         }
7368
7369         #[test]
7370         fn test_drop_messages_peer_disconnect_b() {
7371                 do_test_drop_messages_peer_disconnect(4);
7372                 do_test_drop_messages_peer_disconnect(5);
7373                 do_test_drop_messages_peer_disconnect(6);
7374         }
7375
7376         #[test]
7377         fn test_funding_peer_disconnect() {
7378                 // Test that we can lock in our funding tx while disconnected
7379                 let nodes = create_network(2);
7380                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
7381
7382                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7383                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7384
7385                 confirm_transaction(&nodes[0].chain_monitor, &tx, tx.version);
7386                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7387                 assert_eq!(events_1.len(), 1);
7388                 match events_1[0] {
7389                         MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7390                                 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7391                         },
7392                         _ => panic!("Unexpected event"),
7393                 }
7394
7395                 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7396
7397                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7398                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7399
7400                 confirm_transaction(&nodes[1].chain_monitor, &tx, tx.version);
7401                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7402                 assert_eq!(events_2.len(), 2);
7403                 match events_2[0] {
7404                         MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7405                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7406                         },
7407                         _ => panic!("Unexpected event"),
7408                 }
7409                 match events_2[1] {
7410                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ } => {
7411                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7412                         },
7413                         _ => panic!("Unexpected event"),
7414                 }
7415
7416                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7417
7418                 // TODO: We shouldn't need to manually pass list_usable_chanels here once we support
7419                 // rebroadcasting announcement_signatures upon reconnect.
7420
7421                 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();
7422                 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
7423                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
7424         }
7425
7426         #[test]
7427         fn test_drop_messages_peer_disconnect_dual_htlc() {
7428                 // Test that we can handle reconnecting when both sides of a channel have pending
7429                 // commitment_updates when we disconnect.
7430                 let mut nodes = create_network(2);
7431                 create_announced_chan_between_nodes(&nodes, 0, 1);
7432
7433                 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7434
7435                 // Now try to send a second payment which will fail to send
7436                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7437                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7438
7439                 nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
7440                 check_added_monitors!(nodes[0], 1);
7441
7442                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7443                 assert_eq!(events_1.len(), 1);
7444                 match events_1[0] {
7445                         MessageSendEvent::UpdateHTLCs { .. } => {},
7446                         _ => panic!("Unexpected event"),
7447                 }
7448
7449                 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7450                 check_added_monitors!(nodes[1], 1);
7451
7452                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7453                 assert_eq!(events_2.len(), 1);
7454                 match events_2[0] {
7455                         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 } } => {
7456                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7457                                 assert!(update_add_htlcs.is_empty());
7458                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7459                                 assert!(update_fail_htlcs.is_empty());
7460                                 assert!(update_fail_malformed_htlcs.is_empty());
7461                                 assert!(update_fee.is_none());
7462
7463                                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7464                                 let events_3 = nodes[0].node.get_and_clear_pending_events();
7465                                 assert_eq!(events_3.len(), 1);
7466                                 match events_3[0] {
7467                                         Event::PaymentSent { ref payment_preimage } => {
7468                                                 assert_eq!(*payment_preimage, payment_preimage_1);
7469                                         },
7470                                         _ => panic!("Unexpected event"),
7471                                 }
7472
7473                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
7474                                 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7475                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7476                                 check_added_monitors!(nodes[0], 1);
7477                         },
7478                         _ => panic!("Unexpected event"),
7479                 }
7480
7481                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7482                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7483
7484                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7485                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7486                 assert_eq!(reestablish_1.len(), 1);
7487                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7488                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7489                 assert_eq!(reestablish_2.len(), 1);
7490
7491                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7492                 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7493                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7494                 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7495
7496                 assert!(as_resp.0.is_none());
7497                 assert!(bs_resp.0.is_none());
7498
7499                 assert!(bs_resp.1.is_none());
7500                 assert!(bs_resp.2.is_none());
7501
7502                 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7503
7504                 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
7505                 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
7506                 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7507                 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7508                 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
7509                 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();
7510                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7511                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7512                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7513                 check_added_monitors!(nodes[1], 1);
7514
7515                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap();
7516                 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7517                 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
7518                 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
7519                 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
7520                 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
7521                 assert!(bs_second_commitment_signed.update_fee.is_none());
7522                 check_added_monitors!(nodes[1], 1);
7523
7524                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7525                 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7526                 assert!(as_commitment_signed.update_add_htlcs.is_empty());
7527                 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
7528                 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
7529                 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
7530                 assert!(as_commitment_signed.update_fee.is_none());
7531                 check_added_monitors!(nodes[0], 1);
7532
7533                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
7534                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7535                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7536                 check_added_monitors!(nodes[0], 1);
7537
7538                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
7539                 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7540                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7541                 check_added_monitors!(nodes[1], 1);
7542
7543                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7544                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7545                 check_added_monitors!(nodes[1], 1);
7546
7547                 let events_4 = nodes[1].node.get_and_clear_pending_events();
7548                 assert_eq!(events_4.len(), 1);
7549                 match events_4[0] {
7550                         Event::PendingHTLCsForwardable { .. } => { },
7551                         _ => panic!("Unexpected event"),
7552                 };
7553
7554                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7555                 nodes[1].node.process_pending_htlc_forwards();
7556
7557                 let events_5 = nodes[1].node.get_and_clear_pending_events();
7558                 assert_eq!(events_5.len(), 1);
7559                 match events_5[0] {
7560                         Event::PaymentReceived { ref payment_hash, amt: _ } => {
7561                                 assert_eq!(payment_hash_2, *payment_hash);
7562                         },
7563                         _ => panic!("Unexpected event"),
7564                 }
7565
7566                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
7567                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7568                 check_added_monitors!(nodes[0], 1);
7569
7570                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7571         }
7572
7573         #[test]
7574         fn test_simple_monitor_permanent_update_fail() {
7575                 // Test that we handle a simple permanent monitor update failure
7576                 let mut nodes = create_network(2);
7577                 create_announced_chan_between_nodes(&nodes, 0, 1);
7578
7579                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7580                 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7581
7582                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7583                 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route, payment_hash_1) {} else { panic!(); }
7584                 check_added_monitors!(nodes[0], 1);
7585
7586                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7587                 assert_eq!(events_1.len(), 2);
7588                 match events_1[0] {
7589                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7590                         _ => panic!("Unexpected event"),
7591                 };
7592                 match events_1[1] {
7593                         MessageSendEvent::HandleError { node_id, .. } => assert_eq!(node_id, nodes[1].node.get_our_node_id()),
7594                         _ => panic!("Unexpected event"),
7595                 };
7596
7597                 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7598                 // PaymentFailed event
7599
7600                 assert_eq!(nodes[0].node.list_channels().len(), 0);
7601         }
7602
7603         fn do_test_simple_monitor_temporary_update_fail(disconnect: bool) {
7604                 // Test that we can recover from a simple temporary monitor update failure optionally with
7605                 // a disconnect in between
7606                 let mut nodes = create_network(2);
7607                 create_announced_chan_between_nodes(&nodes, 0, 1);
7608
7609                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7610                 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7611
7612                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7613                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_1) {} else { panic!(); }
7614                 check_added_monitors!(nodes[0], 1);
7615
7616                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7617                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7618                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7619
7620                 if disconnect {
7621                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7622                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7623                         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7624                 }
7625
7626                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7627                 nodes[0].node.test_restore_channel_monitor();
7628                 check_added_monitors!(nodes[0], 1);
7629
7630                 let mut events_2 = nodes[0].node.get_and_clear_pending_msg_events();
7631                 assert_eq!(events_2.len(), 1);
7632                 let payment_event = SendEvent::from_event(events_2.pop().unwrap());
7633                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7634                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7635                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7636
7637                 expect_pending_htlcs_forwardable!(nodes[1]);
7638
7639                 let events_3 = nodes[1].node.get_and_clear_pending_events();
7640                 assert_eq!(events_3.len(), 1);
7641                 match events_3[0] {
7642                         Event::PaymentReceived { ref payment_hash, amt } => {
7643                                 assert_eq!(payment_hash_1, *payment_hash);
7644                                 assert_eq!(amt, 1000000);
7645                         },
7646                         _ => panic!("Unexpected event"),
7647                 }
7648
7649                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_1);
7650
7651                 // Now set it to failed again...
7652                 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7653                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7654                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route, payment_hash_2) {} else { panic!(); }
7655                 check_added_monitors!(nodes[0], 1);
7656
7657                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7658                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7659                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7660
7661                 if disconnect {
7662                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7663                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7664                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7665                 }
7666
7667                 // ...and make sure we can force-close a TemporaryFailure channel with a PermanentFailure
7668                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7669                 nodes[0].node.test_restore_channel_monitor();
7670                 check_added_monitors!(nodes[0], 1);
7671
7672                 let events_5 = nodes[0].node.get_and_clear_pending_msg_events();
7673                 assert_eq!(events_5.len(), 1);
7674                 match events_5[0] {
7675                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7676                         _ => panic!("Unexpected event"),
7677                 }
7678
7679                 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7680                 // PaymentFailed event
7681
7682                 assert_eq!(nodes[0].node.list_channels().len(), 0);
7683         }
7684
7685         #[test]
7686         fn test_simple_monitor_temporary_update_fail() {
7687                 do_test_simple_monitor_temporary_update_fail(false);
7688                 do_test_simple_monitor_temporary_update_fail(true);
7689         }
7690
7691         fn do_test_monitor_temporary_update_fail(disconnect_count: usize) {
7692                 let disconnect_flags = 8 | 16;
7693
7694                 // Test that we can recover from a temporary monitor update failure with some in-flight
7695                 // HTLCs going on at the same time potentially with some disconnection thrown in.
7696                 // * First we route a payment, then get a temporary monitor update failure when trying to
7697                 //   route a second payment. We then claim the first payment.
7698                 // * If disconnect_count is set, we will disconnect at this point (which is likely as
7699                 //   TemporaryFailure likely indicates net disconnect which resulted in failing to update
7700                 //   the ChannelMonitor on a watchtower).
7701                 // * If !(disconnect_count & 16) we deliver a update_fulfill_htlc/CS for the first payment
7702                 //   immediately, otherwise we wait sconnect and deliver them via the reconnect
7703                 //   channel_reestablish processing (ie disconnect_count & 16 makes no sense if
7704                 //   disconnect_count & !disconnect_flags is 0).
7705                 // * We then update the channel monitor, reconnecting if disconnect_count is set and walk
7706                 //   through message sending, potentially disconnect/reconnecting multiple times based on
7707                 //   disconnect_count, to get the update_fulfill_htlc through.
7708                 // * We then walk through more message exchanges to get the original update_add_htlc
7709                 //   through, swapping message ordering based on disconnect_count & 8 and optionally
7710                 //   disconnect/reconnecting based on disconnect_count.
7711                 let mut nodes = create_network(2);
7712                 create_announced_chan_between_nodes(&nodes, 0, 1);
7713
7714                 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7715
7716                 // Now try to send a second payment which will fail to send
7717                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7718                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7719
7720                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7721                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_2) {} else { panic!(); }
7722                 check_added_monitors!(nodes[0], 1);
7723
7724                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7725                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7726                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7727
7728                 // Claim the previous payment, which will result in a update_fulfill_htlc/CS from nodes[1]
7729                 // but nodes[0] won't respond since it is frozen.
7730                 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7731                 check_added_monitors!(nodes[1], 1);
7732                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7733                 assert_eq!(events_2.len(), 1);
7734                 let (bs_initial_fulfill, bs_initial_commitment_signed) = match events_2[0] {
7735                         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 } } => {
7736                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7737                                 assert!(update_add_htlcs.is_empty());
7738                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7739                                 assert!(update_fail_htlcs.is_empty());
7740                                 assert!(update_fail_malformed_htlcs.is_empty());
7741                                 assert!(update_fee.is_none());
7742
7743                                 if (disconnect_count & 16) == 0 {
7744                                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7745                                         let events_3 = nodes[0].node.get_and_clear_pending_events();
7746                                         assert_eq!(events_3.len(), 1);
7747                                         match events_3[0] {
7748                                                 Event::PaymentSent { ref payment_preimage } => {
7749                                                         assert_eq!(*payment_preimage, payment_preimage_1);
7750                                                 },
7751                                                 _ => panic!("Unexpected event"),
7752                                         }
7753
7754                                         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) {
7755                                                 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
7756                                         } else { panic!(); }
7757                                 }
7758
7759                                 (update_fulfill_htlcs[0].clone(), commitment_signed.clone())
7760                         },
7761                         _ => panic!("Unexpected event"),
7762                 };
7763
7764                 if disconnect_count & !disconnect_flags > 0 {
7765                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7766                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7767                 }
7768
7769                 // Now fix monitor updating...
7770                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7771                 nodes[0].node.test_restore_channel_monitor();
7772                 check_added_monitors!(nodes[0], 1);
7773
7774                 macro_rules! disconnect_reconnect_peers { () => { {
7775                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7776                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7777
7778                         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7779                         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7780                         assert_eq!(reestablish_1.len(), 1);
7781                         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7782                         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7783                         assert_eq!(reestablish_2.len(), 1);
7784
7785                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7786                         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7787                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7788                         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7789
7790                         assert!(as_resp.0.is_none());
7791                         assert!(bs_resp.0.is_none());
7792
7793                         (reestablish_1, reestablish_2, as_resp, bs_resp)
7794                 } } }
7795
7796                 let (payment_event, initial_revoke_and_ack) = if disconnect_count & !disconnect_flags > 0 {
7797                         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7798                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7799
7800                         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7801                         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7802                         assert_eq!(reestablish_1.len(), 1);
7803                         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7804                         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7805                         assert_eq!(reestablish_2.len(), 1);
7806
7807                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7808                         check_added_monitors!(nodes[0], 0);
7809                         let mut as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7810                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7811                         check_added_monitors!(nodes[1], 0);
7812                         let mut bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7813
7814                         assert!(as_resp.0.is_none());
7815                         assert!(bs_resp.0.is_none());
7816
7817                         assert!(bs_resp.1.is_none());
7818                         if (disconnect_count & 16) == 0 {
7819                                 assert!(bs_resp.2.is_none());
7820
7821                                 assert!(as_resp.1.is_some());
7822                                 assert!(as_resp.2.is_some());
7823                                 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7824                         } else {
7825                                 assert!(bs_resp.2.as_ref().unwrap().update_add_htlcs.is_empty());
7826                                 assert!(bs_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7827                                 assert!(bs_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7828                                 assert!(bs_resp.2.as_ref().unwrap().update_fee.is_none());
7829                                 assert!(bs_resp.2.as_ref().unwrap().update_fulfill_htlcs == vec![bs_initial_fulfill]);
7830                                 assert!(bs_resp.2.as_ref().unwrap().commitment_signed == bs_initial_commitment_signed);
7831
7832                                 assert!(as_resp.1.is_none());
7833
7834                                 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();
7835                                 let events_3 = nodes[0].node.get_and_clear_pending_events();
7836                                 assert_eq!(events_3.len(), 1);
7837                                 match events_3[0] {
7838                                         Event::PaymentSent { ref payment_preimage } => {
7839                                                 assert_eq!(*payment_preimage, payment_preimage_1);
7840                                         },
7841                                         _ => panic!("Unexpected event"),
7842                                 }
7843
7844                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7845                                 let as_resp_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7846                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7847                                 check_added_monitors!(nodes[0], 1);
7848
7849                                 as_resp.1 = Some(as_resp_raa);
7850                                 bs_resp.2 = None;
7851                         }
7852
7853                         if disconnect_count & !disconnect_flags > 1 {
7854                                 let (second_reestablish_1, second_reestablish_2, second_as_resp, second_bs_resp) = disconnect_reconnect_peers!();
7855
7856                                 if (disconnect_count & 16) == 0 {
7857                                         assert!(reestablish_1 == second_reestablish_1);
7858                                         assert!(reestablish_2 == second_reestablish_2);
7859                                 }
7860                                 assert!(as_resp == second_as_resp);
7861                                 assert!(bs_resp == second_bs_resp);
7862                         }
7863
7864                         (SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), as_resp.2.unwrap()), as_resp.1.unwrap())
7865                 } else {
7866                         let mut events_4 = nodes[0].node.get_and_clear_pending_msg_events();
7867                         assert_eq!(events_4.len(), 2);
7868                         (SendEvent::from_event(events_4.remove(0)), match events_4[0] {
7869                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
7870                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7871                                         msg.clone()
7872                                 },
7873                                 _ => panic!("Unexpected event"),
7874                         })
7875                 };
7876
7877                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7878
7879                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7880                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7881                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7882                 // nodes[1] is awaiting an RAA from nodes[0] still so get_event_msg's assert(len == 1) passes
7883                 check_added_monitors!(nodes[1], 1);
7884
7885                 if disconnect_count & !disconnect_flags > 2 {
7886                         let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7887
7888                         assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7889                         assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7890
7891                         assert!(as_resp.2.is_none());
7892                         assert!(bs_resp.2.is_none());
7893                 }
7894
7895                 let as_commitment_update;
7896                 let bs_second_commitment_update;
7897
7898                 macro_rules! handle_bs_raa { () => {
7899                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7900                         as_commitment_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7901                         assert!(as_commitment_update.update_add_htlcs.is_empty());
7902                         assert!(as_commitment_update.update_fulfill_htlcs.is_empty());
7903                         assert!(as_commitment_update.update_fail_htlcs.is_empty());
7904                         assert!(as_commitment_update.update_fail_malformed_htlcs.is_empty());
7905                         assert!(as_commitment_update.update_fee.is_none());
7906                         check_added_monitors!(nodes[0], 1);
7907                 } }
7908
7909                 macro_rules! handle_initial_raa { () => {
7910                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &initial_revoke_and_ack).unwrap();
7911                         bs_second_commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7912                         assert!(bs_second_commitment_update.update_add_htlcs.is_empty());
7913                         assert!(bs_second_commitment_update.update_fulfill_htlcs.is_empty());
7914                         assert!(bs_second_commitment_update.update_fail_htlcs.is_empty());
7915                         assert!(bs_second_commitment_update.update_fail_malformed_htlcs.is_empty());
7916                         assert!(bs_second_commitment_update.update_fee.is_none());
7917                         check_added_monitors!(nodes[1], 1);
7918                 } }
7919
7920                 if (disconnect_count & 8) == 0 {
7921                         handle_bs_raa!();
7922
7923                         if disconnect_count & !disconnect_flags > 3 {
7924                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7925
7926                                 assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7927                                 assert!(bs_resp.1.is_none());
7928
7929                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7930                                 assert!(bs_resp.2.is_none());
7931
7932                                 assert!(as_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7933                         }
7934
7935                         handle_initial_raa!();
7936
7937                         if disconnect_count & !disconnect_flags > 4 {
7938                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7939
7940                                 assert!(as_resp.1.is_none());
7941                                 assert!(bs_resp.1.is_none());
7942
7943                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7944                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7945                         }
7946                 } else {
7947                         handle_initial_raa!();
7948
7949                         if disconnect_count & !disconnect_flags > 3 {
7950                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7951
7952                                 assert!(as_resp.1.is_none());
7953                                 assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7954
7955                                 assert!(as_resp.2.is_none());
7956                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7957
7958                                 assert!(bs_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7959                         }
7960
7961                         handle_bs_raa!();
7962
7963                         if disconnect_count & !disconnect_flags > 4 {
7964                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7965
7966                                 assert!(as_resp.1.is_none());
7967                                 assert!(bs_resp.1.is_none());
7968
7969                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7970                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7971                         }
7972                 }
7973
7974                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_update.commitment_signed).unwrap();
7975                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7976                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7977                 check_added_monitors!(nodes[0], 1);
7978
7979                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_update.commitment_signed).unwrap();
7980                 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7981                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7982                 check_added_monitors!(nodes[1], 1);
7983
7984                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7985                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7986                 check_added_monitors!(nodes[1], 1);
7987
7988                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
7989                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7990                 check_added_monitors!(nodes[0], 1);
7991
7992                 expect_pending_htlcs_forwardable!(nodes[1]);
7993
7994                 let events_5 = nodes[1].node.get_and_clear_pending_events();
7995                 assert_eq!(events_5.len(), 1);
7996                 match events_5[0] {
7997                         Event::PaymentReceived { ref payment_hash, amt } => {
7998                                 assert_eq!(payment_hash_2, *payment_hash);
7999                                 assert_eq!(amt, 1000000);
8000                         },
8001                         _ => panic!("Unexpected event"),
8002                 }
8003
8004                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
8005         }
8006
8007         #[test]
8008         fn test_monitor_temporary_update_fail_a() {
8009                 do_test_monitor_temporary_update_fail(0);
8010                 do_test_monitor_temporary_update_fail(1);
8011                 do_test_monitor_temporary_update_fail(2);
8012                 do_test_monitor_temporary_update_fail(3);
8013                 do_test_monitor_temporary_update_fail(4);
8014                 do_test_monitor_temporary_update_fail(5);
8015         }
8016
8017         #[test]
8018         fn test_monitor_temporary_update_fail_b() {
8019                 do_test_monitor_temporary_update_fail(2 | 8);
8020                 do_test_monitor_temporary_update_fail(3 | 8);
8021                 do_test_monitor_temporary_update_fail(4 | 8);
8022                 do_test_monitor_temporary_update_fail(5 | 8);
8023         }
8024
8025         #[test]
8026         fn test_monitor_temporary_update_fail_c() {
8027                 do_test_monitor_temporary_update_fail(1 | 16);
8028                 do_test_monitor_temporary_update_fail(2 | 16);
8029                 do_test_monitor_temporary_update_fail(3 | 16);
8030                 do_test_monitor_temporary_update_fail(2 | 8 | 16);
8031                 do_test_monitor_temporary_update_fail(3 | 8 | 16);
8032         }
8033
8034         #[test]
8035         fn test_monitor_update_fail_cs() {
8036                 // Tests handling of a monitor update failure when processing an incoming commitment_signed
8037                 let mut nodes = create_network(2);
8038                 create_announced_chan_between_nodes(&nodes, 0, 1);
8039
8040                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8041                 let (payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
8042                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
8043                 check_added_monitors!(nodes[0], 1);
8044
8045                 let send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8046                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8047
8048                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8049                 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() {
8050                         assert_eq!(err, "Failed to update ChannelMonitor");
8051                 } else { panic!(); }
8052                 check_added_monitors!(nodes[1], 1);
8053                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8054
8055                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8056                 nodes[1].node.test_restore_channel_monitor();
8057                 check_added_monitors!(nodes[1], 1);
8058                 let responses = nodes[1].node.get_and_clear_pending_msg_events();
8059                 assert_eq!(responses.len(), 2);
8060
8061                 match responses[0] {
8062                         MessageSendEvent::SendRevokeAndACK { ref msg, ref node_id } => {
8063                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8064                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &msg).unwrap();
8065                                 check_added_monitors!(nodes[0], 1);
8066                         },
8067                         _ => panic!("Unexpected event"),
8068                 }
8069                 match responses[1] {
8070                         MessageSendEvent::UpdateHTLCs { ref updates, ref node_id } => {
8071                                 assert!(updates.update_add_htlcs.is_empty());
8072                                 assert!(updates.update_fulfill_htlcs.is_empty());
8073                                 assert!(updates.update_fail_htlcs.is_empty());
8074                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8075                                 assert!(updates.update_fee.is_none());
8076                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8077
8078                                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8079                                 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() {
8080                                         assert_eq!(err, "Failed to update ChannelMonitor");
8081                                 } else { panic!(); }
8082                                 check_added_monitors!(nodes[0], 1);
8083                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8084                         },
8085                         _ => panic!("Unexpected event"),
8086                 }
8087
8088                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
8089                 nodes[0].node.test_restore_channel_monitor();
8090                 check_added_monitors!(nodes[0], 1);
8091
8092                 let final_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8093                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &final_raa).unwrap();
8094                 check_added_monitors!(nodes[1], 1);
8095
8096                 let mut events = nodes[1].node.get_and_clear_pending_events();
8097                 assert_eq!(events.len(), 1);
8098                 match events[0] {
8099                         Event::PendingHTLCsForwardable { .. } => { },
8100                         _ => panic!("Unexpected event"),
8101                 };
8102                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8103                 nodes[1].node.process_pending_htlc_forwards();
8104
8105                 events = nodes[1].node.get_and_clear_pending_events();
8106                 assert_eq!(events.len(), 1);
8107                 match events[0] {
8108                         Event::PaymentReceived { payment_hash, amt } => {
8109                                 assert_eq!(payment_hash, our_payment_hash);
8110                                 assert_eq!(amt, 1000000);
8111                         },
8112                         _ => panic!("Unexpected event"),
8113                 };
8114
8115                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
8116         }
8117
8118         fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) {
8119                 // Tests handling of a monitor update failure when processing an incoming RAA
8120                 let mut nodes = create_network(3);
8121                 create_announced_chan_between_nodes(&nodes, 0, 1);
8122                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
8123
8124                 // Rebalance a bit so that we can send backwards from 2 to 1.
8125                 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 5000000);
8126
8127                 // Route a first payment that we'll fail backwards
8128                 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
8129
8130                 // Fail the payment backwards, failing the monitor update on nodes[1]'s receipt of the RAA
8131                 assert!(nodes[2].node.fail_htlc_backwards(&payment_hash_1, 0));
8132                 check_added_monitors!(nodes[2], 1);
8133
8134                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8135                 assert!(updates.update_add_htlcs.is_empty());
8136                 assert!(updates.update_fulfill_htlcs.is_empty());
8137                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8138                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8139                 assert!(updates.update_fee.is_none());
8140                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
8141
8142                 let bs_revoke_and_ack = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
8143                 check_added_monitors!(nodes[0], 0);
8144
8145                 // While the second channel is AwaitingRAA, forward a second payment to get it into the
8146                 // holding cell.
8147                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
8148                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8149                 nodes[0].node.send_payment(route, payment_hash_2).unwrap();
8150                 check_added_monitors!(nodes[0], 1);
8151
8152                 let mut send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8153                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8154                 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false);
8155
8156                 let events_1 = nodes[1].node.get_and_clear_pending_events();
8157                 assert_eq!(events_1.len(), 1);
8158                 match events_1[0] {
8159                         Event::PendingHTLCsForwardable { .. } => { },
8160                         _ => panic!("Unexpected event"),
8161                 };
8162
8163                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8164                 nodes[1].node.process_pending_htlc_forwards();
8165                 check_added_monitors!(nodes[1], 0);
8166                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8167
8168                 // Now fail monitor updating.
8169                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8170                 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() {
8171                         assert_eq!(err, "Failed to update ChannelMonitor");
8172                 } else { panic!(); }
8173                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8174                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8175                 check_added_monitors!(nodes[1], 1);
8176
8177                 // Attempt to forward a third payment but fail due to the second channel being unavailable
8178                 // for forwarding.
8179
8180                 let (_, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
8181                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8182                 nodes[0].node.send_payment(route, payment_hash_3).unwrap();
8183                 check_added_monitors!(nodes[0], 1);
8184
8185                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(()); // We succeed in updating the monitor for the first channel
8186                 send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8187                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8188                 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
8189                 check_added_monitors!(nodes[1], 0);
8190
8191                 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8192                 assert_eq!(events_2.len(), 1);
8193                 match events_2.remove(0) {
8194                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
8195                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8196                                 assert!(updates.update_fulfill_htlcs.is_empty());
8197                                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8198                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8199                                 assert!(updates.update_add_htlcs.is_empty());
8200                                 assert!(updates.update_fee.is_none());
8201
8202                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
8203                                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
8204
8205                                 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
8206                                 assert_eq!(msg_events.len(), 1);
8207                                 match msg_events[0] {
8208                                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
8209                                                 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
8210                                                 assert_eq!(msg.contents.flags & 2, 2); // temp disabled
8211                                         },
8212                                         _ => panic!("Unexpected event"),
8213                                 }
8214
8215                                 let events = nodes[0].node.get_and_clear_pending_events();
8216                                 assert_eq!(events.len(), 1);
8217                                 if let Event::PaymentFailed { payment_hash, rejected_by_dest, .. } = events[0] {
8218                                         assert_eq!(payment_hash, payment_hash_3);
8219                                         assert!(!rejected_by_dest);
8220                                 } else { panic!("Unexpected event!"); }
8221                         },
8222                         _ => panic!("Unexpected event type!"),
8223                 };
8224
8225                 let (payment_preimage_4, payment_hash_4) = if test_ignore_second_cs {
8226                         // Try to route another payment backwards from 2 to make sure 1 holds off on responding
8227                         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[0]);
8228                         let route = nodes[2].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8229                         nodes[2].node.send_payment(route, payment_hash_4).unwrap();
8230                         check_added_monitors!(nodes[2], 1);
8231
8232                         send_event = SendEvent::from_event(nodes[2].node.get_and_clear_pending_msg_events().remove(0));
8233                         nodes[1].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8234                         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) {
8235                                 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
8236                         } else { panic!(); }
8237                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8238                         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8239                         (Some(payment_preimage_4), Some(payment_hash_4))
8240                 } else { (None, None) };
8241
8242                 // Restore monitor updating, ensuring we immediately get a fail-back update and a
8243                 // update_add update.
8244                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8245                 nodes[1].node.test_restore_channel_monitor();
8246                 check_added_monitors!(nodes[1], 2);
8247
8248                 let mut events_3 = nodes[1].node.get_and_clear_pending_msg_events();
8249                 if test_ignore_second_cs {
8250                         assert_eq!(events_3.len(), 3);
8251                 } else {
8252                         assert_eq!(events_3.len(), 2);
8253                 }
8254
8255                 // Note that the ordering of the events for different nodes is non-prescriptive, though the
8256                 // ordering of the two events that both go to nodes[2] have to stay in the same order.
8257                 let messages_a = match events_3.pop().unwrap() {
8258                         MessageSendEvent::UpdateHTLCs { node_id, mut updates } => {
8259                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8260                                 assert!(updates.update_fulfill_htlcs.is_empty());
8261                                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8262                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8263                                 assert!(updates.update_add_htlcs.is_empty());
8264                                 assert!(updates.update_fee.is_none());
8265                                 (updates.update_fail_htlcs.remove(0), updates.commitment_signed)
8266                         },
8267                         _ => panic!("Unexpected event type!"),
8268                 };
8269                 let raa = if test_ignore_second_cs {
8270                         match events_3.remove(1) {
8271                                 MessageSendEvent::SendRevokeAndACK { node_id, msg } => {
8272                                         assert_eq!(node_id, nodes[2].node.get_our_node_id());
8273                                         Some(msg.clone())
8274                                 },
8275                                 _ => panic!("Unexpected event"),
8276                         }
8277                 } else { None };
8278                 let send_event_b = SendEvent::from_event(events_3.remove(0));
8279                 assert_eq!(send_event_b.node_id, nodes[2].node.get_our_node_id());
8280
8281                 // Now deliver the new messages...
8282
8283                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &messages_a.0).unwrap();
8284                 commitment_signed_dance!(nodes[0], nodes[1], messages_a.1, false);
8285                 let events_4 = nodes[0].node.get_and_clear_pending_events();
8286                 assert_eq!(events_4.len(), 1);
8287                 if let Event::PaymentFailed { payment_hash, rejected_by_dest, .. } = events_4[0] {
8288                         assert_eq!(payment_hash, payment_hash_1);
8289                         assert!(rejected_by_dest);
8290                 } else { panic!("Unexpected event!"); }
8291
8292                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event_b.msgs[0]).unwrap();
8293                 if test_ignore_second_cs {
8294                         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event_b.commitment_msg).unwrap();
8295                         check_added_monitors!(nodes[2], 1);
8296                         let bs_revoke_and_ack = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8297                         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa.unwrap()).unwrap();
8298                         check_added_monitors!(nodes[2], 1);
8299                         let bs_cs = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8300                         assert!(bs_cs.update_add_htlcs.is_empty());
8301                         assert!(bs_cs.update_fail_htlcs.is_empty());
8302                         assert!(bs_cs.update_fail_malformed_htlcs.is_empty());
8303                         assert!(bs_cs.update_fulfill_htlcs.is_empty());
8304                         assert!(bs_cs.update_fee.is_none());
8305
8306                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
8307                         check_added_monitors!(nodes[1], 1);
8308                         let as_cs = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
8309                         assert!(as_cs.update_add_htlcs.is_empty());
8310                         assert!(as_cs.update_fail_htlcs.is_empty());
8311                         assert!(as_cs.update_fail_malformed_htlcs.is_empty());
8312                         assert!(as_cs.update_fulfill_htlcs.is_empty());
8313                         assert!(as_cs.update_fee.is_none());
8314
8315                         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_cs.commitment_signed).unwrap();
8316                         check_added_monitors!(nodes[1], 1);
8317                         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
8318
8319                         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_cs.commitment_signed).unwrap();
8320                         check_added_monitors!(nodes[2], 1);
8321                         let bs_second_raa = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8322
8323                         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
8324                         check_added_monitors!(nodes[2], 1);
8325                         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
8326
8327                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_second_raa).unwrap();
8328                         check_added_monitors!(nodes[1], 1);
8329                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8330                 } else {
8331                         commitment_signed_dance!(nodes[2], nodes[1], send_event_b.commitment_msg, false);
8332                 }
8333
8334                 let events_5 = nodes[2].node.get_and_clear_pending_events();
8335                 assert_eq!(events_5.len(), 1);
8336                 match events_5[0] {
8337                         Event::PendingHTLCsForwardable { .. } => { },
8338                         _ => panic!("Unexpected event"),
8339                 };
8340
8341                 nodes[2].node.channel_state.lock().unwrap().next_forward = Instant::now();
8342                 nodes[2].node.process_pending_htlc_forwards();
8343
8344                 let events_6 = nodes[2].node.get_and_clear_pending_events();
8345                 assert_eq!(events_6.len(), 1);
8346                 match events_6[0] {
8347                         Event::PaymentReceived { payment_hash, .. } => { assert_eq!(payment_hash, payment_hash_2); },
8348                         _ => panic!("Unexpected event"),
8349                 };
8350
8351                 if test_ignore_second_cs {
8352                         let events_7 = nodes[1].node.get_and_clear_pending_events();
8353                         assert_eq!(events_7.len(), 1);
8354                         match events_7[0] {
8355                                 Event::PendingHTLCsForwardable { .. } => { },
8356                                 _ => panic!("Unexpected event"),
8357                         };
8358
8359                         nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8360                         nodes[1].node.process_pending_htlc_forwards();
8361                         check_added_monitors!(nodes[1], 1);
8362
8363                         send_event = SendEvent::from_node(&nodes[1]);
8364                         assert_eq!(send_event.node_id, nodes[0].node.get_our_node_id());
8365                         assert_eq!(send_event.msgs.len(), 1);
8366                         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8367                         commitment_signed_dance!(nodes[0], nodes[1], send_event.commitment_msg, false);
8368
8369                         let events_8 = nodes[0].node.get_and_clear_pending_events();
8370                         assert_eq!(events_8.len(), 1);
8371                         match events_8[0] {
8372                                 Event::PendingHTLCsForwardable { .. } => { },
8373                                 _ => panic!("Unexpected event"),
8374                         };
8375
8376                         nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
8377                         nodes[0].node.process_pending_htlc_forwards();
8378
8379                         let events_9 = nodes[0].node.get_and_clear_pending_events();
8380                         assert_eq!(events_9.len(), 1);
8381                         match events_9[0] {
8382                                 Event::PaymentReceived { payment_hash, .. } => assert_eq!(payment_hash, payment_hash_4.unwrap()),
8383                                 _ => panic!("Unexpected event"),
8384                         };
8385                         claim_payment(&nodes[2], &[&nodes[1], &nodes[0]], payment_preimage_4.unwrap());
8386                 }
8387
8388                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
8389         }
8390
8391         #[test]
8392         fn test_monitor_update_fail_raa() {
8393                 do_test_monitor_update_fail_raa(false);
8394                 do_test_monitor_update_fail_raa(true);
8395         }
8396
8397         #[test]
8398         fn test_monitor_update_fail_reestablish() {
8399                 // Simple test for message retransmission after monitor update failure on
8400                 // channel_reestablish generating a monitor update (which comes from freeing holding cell
8401                 // HTLCs).
8402                 let mut nodes = create_network(3);
8403                 create_announced_chan_between_nodes(&nodes, 0, 1);
8404                 create_announced_chan_between_nodes(&nodes, 1, 2);
8405
8406                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
8407
8408                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8409                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8410
8411                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
8412                 check_added_monitors!(nodes[2], 1);
8413                 let mut updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8414                 assert!(updates.update_add_htlcs.is_empty());
8415                 assert!(updates.update_fail_htlcs.is_empty());
8416                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8417                 assert!(updates.update_fee.is_none());
8418                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8419                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8420                 check_added_monitors!(nodes[1], 1);
8421                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8422                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
8423
8424                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8425                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8426                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8427
8428                 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
8429                 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8430
8431                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
8432
8433                 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() {
8434                         assert_eq!(err, "Failed to update ChannelMonitor");
8435                 } else { panic!(); }
8436                 check_added_monitors!(nodes[1], 1);
8437
8438                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8439                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8440
8441                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8442                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8443
8444                 assert!(as_reestablish == get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()));
8445                 assert!(bs_reestablish == get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id()));
8446
8447                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
8448
8449                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish).unwrap();
8450                 check_added_monitors!(nodes[1], 0);
8451                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8452
8453                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8454                 nodes[1].node.test_restore_channel_monitor();
8455                 check_added_monitors!(nodes[1], 1);
8456
8457                 updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8458                 assert!(updates.update_add_htlcs.is_empty());
8459                 assert!(updates.update_fail_htlcs.is_empty());
8460                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8461                 assert!(updates.update_fee.is_none());
8462                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8463                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8464                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
8465
8466                 let events = nodes[0].node.get_and_clear_pending_events();
8467                 assert_eq!(events.len(), 1);
8468                 match events[0] {
8469                         Event::PaymentSent { payment_preimage, .. } => assert_eq!(payment_preimage, our_payment_preimage),
8470                         _ => panic!("Unexpected event"),
8471                 }
8472         }
8473
8474         #[test]
8475         fn test_invalid_channel_announcement() {
8476                 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
8477                 let secp_ctx = Secp256k1::new();
8478                 let nodes = create_network(2);
8479
8480                 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1]);
8481
8482                 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8483                 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
8484                 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
8485                 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
8486
8487                 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 } );
8488
8489                 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
8490                 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
8491
8492                 let as_network_key = nodes[0].node.get_our_node_id();
8493                 let bs_network_key = nodes[1].node.get_our_node_id();
8494
8495                 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
8496
8497                 let mut chan_announcement;
8498
8499                 macro_rules! dummy_unsigned_msg {
8500                         () => {
8501                                 msgs::UnsignedChannelAnnouncement {
8502                                         features: msgs::GlobalFeatures::new(),
8503                                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
8504                                         short_channel_id: as_chan.get_short_channel_id().unwrap(),
8505                                         node_id_1: if were_node_one { as_network_key } else { bs_network_key },
8506                                         node_id_2: if were_node_one { bs_network_key } else { as_network_key },
8507                                         bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
8508                                         bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
8509                                         excess_data: Vec::new(),
8510                                 };
8511                         }
8512                 }
8513
8514                 macro_rules! sign_msg {
8515                         ($unsigned_msg: expr) => {
8516                                 let msghash = Message::from_slice(&Sha256dHash::from_data(&$unsigned_msg.encode()[..])[..]).unwrap();
8517                                 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
8518                                 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
8519                                 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].node.our_network_key);
8520                                 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].node.our_network_key);
8521                                 chan_announcement = msgs::ChannelAnnouncement {
8522                                         node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
8523                                         node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
8524                                         bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
8525                                         bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
8526                                         contents: $unsigned_msg
8527                                 }
8528                         }
8529                 }
8530
8531                 let unsigned_msg = dummy_unsigned_msg!();
8532                 sign_msg!(unsigned_msg);
8533                 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
8534                 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 } );
8535
8536                 // Configured with Network::Testnet
8537                 let mut unsigned_msg = dummy_unsigned_msg!();
8538                 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
8539                 sign_msg!(unsigned_msg);
8540                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
8541
8542                 let mut unsigned_msg = dummy_unsigned_msg!();
8543                 unsigned_msg.chain_hash = Sha256dHash::from_data(&[1,2,3,4,5,6,7,8,9]);
8544                 sign_msg!(unsigned_msg);
8545                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
8546         }
8547
8548         struct VecWriter(Vec<u8>);
8549         impl Writer for VecWriter {
8550                 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
8551                         self.0.extend_from_slice(buf);
8552                         Ok(())
8553                 }
8554                 fn size_hint(&mut self, size: usize) {
8555                         self.0.reserve_exact(size);
8556                 }
8557         }
8558
8559         #[test]
8560         fn test_no_txn_manager_serialize_deserialize() {
8561                 let mut nodes = create_network(2);
8562
8563                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
8564
8565                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8566
8567                 let nodes_0_serialized = nodes[0].node.encode();
8568                 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8569                 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8570
8571                 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())));
8572                 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8573                 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8574                 assert!(chan_0_monitor_read.is_empty());
8575
8576                 let mut nodes_0_read = &nodes_0_serialized[..];
8577                 let config = UserConfig::new();
8578                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8579                 let (_, nodes_0_deserialized) = {
8580                         let mut channel_monitors = HashMap::new();
8581                         channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8582                         <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8583                                 default_config: config,
8584                                 keys_manager,
8585                                 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8586                                 monitor: nodes[0].chan_monitor.clone(),
8587                                 chain_monitor: nodes[0].chain_monitor.clone(),
8588                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8589                                 logger: Arc::new(test_utils::TestLogger::new()),
8590                                 channel_monitors: &channel_monitors,
8591                         }).unwrap()
8592                 };
8593                 assert!(nodes_0_read.is_empty());
8594
8595                 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8596                 nodes[0].node = Arc::new(nodes_0_deserialized);
8597                 let nodes_0_as_listener: Arc<ChainListener> = nodes[0].node.clone();
8598                 nodes[0].chain_monitor.register_listener(Arc::downgrade(&nodes_0_as_listener));
8599                 assert_eq!(nodes[0].node.list_channels().len(), 1);
8600                 check_added_monitors!(nodes[0], 1);
8601
8602                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8603                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
8604                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8605                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
8606
8607                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
8608                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8609                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
8610                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8611
8612                 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8613                 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8614                 for node in nodes.iter() {
8615                         assert!(node.router.handle_channel_announcement(&announcement).unwrap());
8616                         node.router.handle_channel_update(&as_update).unwrap();
8617                         node.router.handle_channel_update(&bs_update).unwrap();
8618                 }
8619
8620                 send_payment(&nodes[0], &[&nodes[1]], 1000000);
8621         }
8622
8623         #[test]
8624         fn test_simple_manager_serialize_deserialize() {
8625                 let mut nodes = create_network(2);
8626                 create_announced_chan_between_nodes(&nodes, 0, 1);
8627
8628                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8629                 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8630
8631                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8632
8633                 let nodes_0_serialized = nodes[0].node.encode();
8634                 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8635                 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8636
8637                 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())));
8638                 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8639                 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8640                 assert!(chan_0_monitor_read.is_empty());
8641
8642                 let mut nodes_0_read = &nodes_0_serialized[..];
8643                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8644                 let (_, nodes_0_deserialized) = {
8645                         let mut channel_monitors = HashMap::new();
8646                         channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8647                         <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8648                                 default_config: UserConfig::new(),
8649                                 keys_manager,
8650                                 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8651                                 monitor: nodes[0].chan_monitor.clone(),
8652                                 chain_monitor: nodes[0].chain_monitor.clone(),
8653                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8654                                 logger: Arc::new(test_utils::TestLogger::new()),
8655                                 channel_monitors: &channel_monitors,
8656                         }).unwrap()
8657                 };
8658                 assert!(nodes_0_read.is_empty());
8659
8660                 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8661                 nodes[0].node = Arc::new(nodes_0_deserialized);
8662                 check_added_monitors!(nodes[0], 1);
8663
8664                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8665
8666                 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
8667                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
8668         }
8669
8670         #[test]
8671         fn test_manager_serialize_deserialize_inconsistent_monitor() {
8672                 // Test deserializing a ChannelManager with a out-of-date ChannelMonitor
8673                 let mut nodes = create_network(4);
8674                 create_announced_chan_between_nodes(&nodes, 0, 1);
8675                 create_announced_chan_between_nodes(&nodes, 2, 0);
8676                 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3);
8677
8678                 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
8679
8680                 // Serialize the ChannelManager here, but the monitor we keep up-to-date
8681                 let nodes_0_serialized = nodes[0].node.encode();
8682
8683                 route_payment(&nodes[0], &[&nodes[3]], 1000000);
8684                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8685                 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8686                 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8687
8688                 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
8689                 // nodes[3])
8690                 let mut node_0_monitors_serialized = Vec::new();
8691                 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
8692                         let mut writer = VecWriter(Vec::new());
8693                         monitor.1.write_for_disk(&mut writer).unwrap();
8694                         node_0_monitors_serialized.push(writer.0);
8695                 }
8696
8697                 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())));
8698                 let mut node_0_monitors = Vec::new();
8699                 for serialized in node_0_monitors_serialized.iter() {
8700                         let mut read = &serialized[..];
8701                         let (_, monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
8702                         assert!(read.is_empty());
8703                         node_0_monitors.push(monitor);
8704                 }
8705
8706                 let mut nodes_0_read = &nodes_0_serialized[..];
8707                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8708                 let (_, nodes_0_deserialized) = <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8709                         default_config: UserConfig::new(),
8710                         keys_manager,
8711                         fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8712                         monitor: nodes[0].chan_monitor.clone(),
8713                         chain_monitor: nodes[0].chain_monitor.clone(),
8714                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8715                         logger: Arc::new(test_utils::TestLogger::new()),
8716                         channel_monitors: &node_0_monitors.iter().map(|monitor| { (monitor.get_funding_txo().unwrap(), monitor) }).collect(),
8717                 }).unwrap();
8718                 assert!(nodes_0_read.is_empty());
8719
8720                 { // Channel close should result in a commitment tx and an HTLC tx
8721                         let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8722                         assert_eq!(txn.len(), 2);
8723                         assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
8724                         assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
8725                 }
8726
8727                 for monitor in node_0_monitors.drain(..) {
8728                         assert!(nodes[0].chan_monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor).is_ok());
8729                         check_added_monitors!(nodes[0], 1);
8730                 }
8731                 nodes[0].node = Arc::new(nodes_0_deserialized);
8732
8733                 // nodes[1] and nodes[2] have no lost state with nodes[0]...
8734                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8735                 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8736                 //... and we can even still claim the payment!
8737                 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
8738
8739                 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id());
8740                 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8741                 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id());
8742                 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) {
8743                         assert_eq!(msg.channel_id, channel_id);
8744                 } else { panic!("Unexpected result"); }
8745         }
8746
8747         macro_rules! check_spendable_outputs {
8748                 ($node: expr, $der_idx: expr) => {
8749                         {
8750                                 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
8751                                 let mut txn = Vec::new();
8752                                 for event in events {
8753                                         match event {
8754                                                 Event::SpendableOutputs { ref outputs } => {
8755                                                         for outp in outputs {
8756                                                                 match *outp {
8757                                                                         SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
8758                                                                                 let input = TxIn {
8759                                                                                         previous_output: outpoint.clone(),
8760                                                                                         script_sig: Script::new(),
8761                                                                                         sequence: 0,
8762                                                                                         witness: Vec::new(),
8763                                                                                 };
8764                                                                                 let outp = TxOut {
8765                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8766                                                                                         value: output.value,
8767                                                                                 };
8768                                                                                 let mut spend_tx = Transaction {
8769                                                                                         version: 2,
8770                                                                                         lock_time: 0,
8771                                                                                         input: vec![input],
8772                                                                                         output: vec![outp],
8773                                                                                 };
8774                                                                                 let secp_ctx = Secp256k1::new();
8775                                                                                 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
8776                                                                                 let witness_script = Address::p2pkh(&remotepubkey, Network::Testnet).script_pubkey();
8777                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8778                                                                                 let remotesig = secp_ctx.sign(&sighash, key);
8779                                                                                 spend_tx.input[0].witness.push(remotesig.serialize_der(&secp_ctx).to_vec());
8780                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8781                                                                                 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
8782                                                                                 txn.push(spend_tx);
8783                                                                         },
8784                                                                         SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
8785                                                                                 let input = TxIn {
8786                                                                                         previous_output: outpoint.clone(),
8787                                                                                         script_sig: Script::new(),
8788                                                                                         sequence: *to_self_delay as u32,
8789                                                                                         witness: Vec::new(),
8790                                                                                 };
8791                                                                                 let outp = TxOut {
8792                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8793                                                                                         value: output.value,
8794                                                                                 };
8795                                                                                 let mut spend_tx = Transaction {
8796                                                                                         version: 2,
8797                                                                                         lock_time: 0,
8798                                                                                         input: vec![input],
8799                                                                                         output: vec![outp],
8800                                                                                 };
8801                                                                                 let secp_ctx = Secp256k1::new();
8802                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
8803                                                                                 let local_delaysig = secp_ctx.sign(&sighash, key);
8804                                                                                 spend_tx.input[0].witness.push(local_delaysig.serialize_der(&secp_ctx).to_vec());
8805                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8806                                                                                 spend_tx.input[0].witness.push(vec!(0));
8807                                                                                 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
8808                                                                                 txn.push(spend_tx);
8809                                                                         },
8810                                                                         SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
8811                                                                                 let secp_ctx = Secp256k1::new();
8812                                                                                 let input = TxIn {
8813                                                                                         previous_output: outpoint.clone(),
8814                                                                                         script_sig: Script::new(),
8815                                                                                         sequence: 0,
8816                                                                                         witness: Vec::new(),
8817                                                                                 };
8818                                                                                 let outp = TxOut {
8819                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8820                                                                                         value: output.value,
8821                                                                                 };
8822                                                                                 let mut spend_tx = Transaction {
8823                                                                                         version: 2,
8824                                                                                         lock_time: 0,
8825                                                                                         input: vec![input],
8826                                                                                         output: vec![outp.clone()],
8827                                                                                 };
8828                                                                                 let secret = {
8829                                                                                         match ExtendedPrivKey::new_master(&secp_ctx, Network::Testnet, &$node.node_seed) {
8830                                                                                                 Ok(master_key) => {
8831                                                                                                         match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx)) {
8832                                                                                                                 Ok(key) => key,
8833                                                                                                                 Err(_) => panic!("Your RNG is busted"),
8834                                                                                                         }
8835                                                                                                 }
8836                                                                                                 Err(_) => panic!("Your rng is busted"),
8837                                                                                         }
8838                                                                                 };
8839                                                                                 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
8840                                                                                 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
8841                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8842                                                                                 let sig = secp_ctx.sign(&sighash, &secret.secret_key);
8843                                                                                 spend_tx.input[0].witness.push(sig.serialize_der(&secp_ctx).to_vec());
8844                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8845                                                                                 spend_tx.input[0].witness.push(pubkey.serialize().to_vec());
8846                                                                                 txn.push(spend_tx);
8847                                                                         },
8848                                                                 }
8849                                                         }
8850                                                 },
8851                                                 _ => panic!("Unexpected event"),
8852                                         };
8853                                 }
8854                                 txn
8855                         }
8856                 }
8857         }
8858
8859         #[test]
8860         fn test_claim_sizeable_push_msat() {
8861                 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
8862                 let nodes = create_network(2);
8863
8864                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8865                 nodes[1].node.force_close_channel(&chan.2);
8866                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8867                 match events[0] {
8868                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8869                         _ => panic!("Unexpected event"),
8870                 }
8871                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8872                 assert_eq!(node_txn.len(), 1);
8873                 check_spends!(node_txn[0], chan.3.clone());
8874                 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
8875
8876                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8877                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8878                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8879                 assert_eq!(spend_txn.len(), 1);
8880                 check_spends!(spend_txn[0], node_txn[0].clone());
8881         }
8882
8883         #[test]
8884         fn test_claim_on_remote_sizeable_push_msat() {
8885                 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8886                 // to_remote output is encumbered by a P2WPKH
8887
8888                 let nodes = create_network(2);
8889
8890                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8891                 nodes[0].node.force_close_channel(&chan.2);
8892                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8893                 match events[0] {
8894                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8895                         _ => panic!("Unexpected event"),
8896                 }
8897                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8898                 assert_eq!(node_txn.len(), 1);
8899                 check_spends!(node_txn[0], chan.3.clone());
8900                 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
8901
8902                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8903                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8904                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8905                 match events[0] {
8906                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8907                         _ => panic!("Unexpected event"),
8908                 }
8909                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8910                 assert_eq!(spend_txn.len(), 2);
8911                 assert_eq!(spend_txn[0], spend_txn[1]);
8912                 check_spends!(spend_txn[0], node_txn[0].clone());
8913         }
8914
8915         #[test]
8916         fn test_claim_on_remote_revoked_sizeable_push_msat() {
8917                 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8918                 // to_remote output is encumbered by a P2WPKH
8919
8920                 let nodes = create_network(2);
8921
8922                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
8923                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8924                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
8925                 assert_eq!(revoked_local_txn[0].input.len(), 1);
8926                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8927
8928                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8929                 let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8930                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
8931                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8932                 match events[0] {
8933                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8934                         _ => panic!("Unexpected event"),
8935                 }
8936                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8937                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8938                 assert_eq!(spend_txn.len(), 4);
8939                 assert_eq!(spend_txn[0], spend_txn[2]); // to_remote output on revoked remote commitment_tx
8940                 check_spends!(spend_txn[0], revoked_local_txn[0].clone());
8941                 assert_eq!(spend_txn[1], spend_txn[3]); // to_local output on local commitment tx
8942                 check_spends!(spend_txn[1], node_txn[0].clone());
8943         }
8944
8945         #[test]
8946         fn test_static_spendable_outputs_preimage_tx() {
8947                 let nodes = create_network(2);
8948
8949                 // Create some initial channels
8950                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8951
8952                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8953
8954                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8955                 assert_eq!(commitment_tx[0].input.len(), 1);
8956                 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
8957
8958                 // Settle A's commitment tx on B's chain
8959                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8960                 assert!(nodes[1].node.claim_funds(payment_preimage));
8961                 check_added_monitors!(nodes[1], 1);
8962                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
8963                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8964                 match events[0] {
8965                         MessageSendEvent::UpdateHTLCs { .. } => {},
8966                         _ => panic!("Unexpected event"),
8967                 }
8968                 match events[1] {
8969                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8970                         _ => panic!("Unexepected event"),
8971                 }
8972
8973                 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
8974                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 1 (local commitment tx), ChannelMonitor: 2 (1 preimage tx) * 2 (block-rescan)
8975                 check_spends!(node_txn[0], commitment_tx[0].clone());
8976                 assert_eq!(node_txn[0], node_txn[2]);
8977                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8978                 check_spends!(node_txn[1], chan_1.3.clone());
8979
8980                 let spend_txn = check_spendable_outputs!(nodes[1], 1); // , 0, 0, 1, 1);
8981                 assert_eq!(spend_txn.len(), 2);
8982                 assert_eq!(spend_txn[0], spend_txn[1]);
8983                 check_spends!(spend_txn[0], node_txn[0].clone());
8984         }
8985
8986         #[test]
8987         fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
8988                 let nodes = create_network(2);
8989
8990                 // Create some initial channels
8991                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8992
8993                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8994                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
8995                 assert_eq!(revoked_local_txn[0].input.len(), 1);
8996                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
8997
8998                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8999
9000                 let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9001                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9002                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9003                 match events[0] {
9004                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9005                         _ => panic!("Unexpected event"),
9006                 }
9007                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9008                 assert_eq!(node_txn.len(), 3);
9009                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]);
9010                 assert_eq!(node_txn[0].input.len(), 2);
9011                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
9012
9013                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9014                 assert_eq!(spend_txn.len(), 2);
9015                 assert_eq!(spend_txn[0], spend_txn[1]);
9016                 check_spends!(spend_txn[0], node_txn[0].clone());
9017         }
9018
9019         #[test]
9020         fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
9021                 let nodes = create_network(2);
9022
9023                 // Create some initial channels
9024                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9025
9026                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9027                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9028                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9029                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9030
9031                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9032
9033                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9034                 // A will generate HTLC-Timeout from revoked commitment tx
9035                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9036                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9037                 match events[0] {
9038                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9039                         _ => panic!("Unexpected event"),
9040                 }
9041                 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9042                 assert_eq!(revoked_htlc_txn.len(), 3);
9043                 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
9044                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
9045                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9046                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
9047                 check_spends!(revoked_htlc_txn[1], chan_1.3.clone());
9048
9049                 // B will generate justice tx from A's revoked commitment/HTLC tx
9050                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
9051                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9052                 match events[0] {
9053                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9054                         _ => panic!("Unexpected event"),
9055                 }
9056
9057                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9058                 assert_eq!(node_txn.len(), 4);
9059                 assert_eq!(node_txn[3].input.len(), 1);
9060                 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
9061
9062                 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
9063                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9064                 assert_eq!(spend_txn.len(), 3);
9065                 assert_eq!(spend_txn[0], spend_txn[1]);
9066                 check_spends!(spend_txn[0], node_txn[0].clone());
9067                 check_spends!(spend_txn[2], node_txn[3].clone());
9068         }
9069
9070         #[test]
9071         fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
9072                 let nodes = create_network(2);
9073
9074                 // Create some initial channels
9075                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9076
9077                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9078                 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9079                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9080                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9081
9082                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9083
9084                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9085                 // B will generate HTLC-Success from revoked commitment tx
9086                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9087                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9088                 match events[0] {
9089                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9090                         _ => panic!("Unexpected event"),
9091                 }
9092                 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9093
9094                 assert_eq!(revoked_htlc_txn.len(), 3);
9095                 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
9096                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
9097                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9098                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
9099
9100                 // A will generate justice tx from B's revoked commitment/HTLC tx
9101                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
9102                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9103                 match events[0] {
9104                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9105                         _ => panic!("Unexpected event"),
9106                 }
9107
9108                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9109                 assert_eq!(node_txn.len(), 4);
9110                 assert_eq!(node_txn[3].input.len(), 1);
9111                 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
9112
9113                 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
9114                 let spend_txn = check_spendable_outputs!(nodes[0], 1);
9115                 assert_eq!(spend_txn.len(), 5);
9116                 assert_eq!(spend_txn[0], spend_txn[2]);
9117                 assert_eq!(spend_txn[1], spend_txn[3]);
9118                 check_spends!(spend_txn[0], revoked_local_txn[0].clone()); // spending to_remote output from revoked local tx
9119                 check_spends!(spend_txn[1], node_txn[2].clone()); // spending justice tx output from revoked local tx htlc received output
9120                 check_spends!(spend_txn[4], node_txn[3].clone()); // spending justice tx output on htlc success tx
9121         }
9122
9123         #[test]
9124         fn test_onchain_to_onchain_claim() {
9125                 // Test that in case of channel closure, we detect the state of output thanks to
9126                 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
9127                 // First, have C claim an HTLC against its own latest commitment transaction.
9128                 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
9129                 // channel.
9130                 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
9131                 // gets broadcast.
9132
9133                 let nodes = create_network(3);
9134
9135                 // Create some initial channels
9136                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9137                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
9138
9139                 // Rebalance the network a bit by relaying one payment through all the channels ...
9140                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
9141                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
9142
9143                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
9144                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9145                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
9146                 check_spends!(commitment_tx[0], chan_2.3.clone());
9147                 nodes[2].node.claim_funds(payment_preimage);
9148                 check_added_monitors!(nodes[2], 1);
9149                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9150                 assert!(updates.update_add_htlcs.is_empty());
9151                 assert!(updates.update_fail_htlcs.is_empty());
9152                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
9153                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9154
9155                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
9156                 let events = nodes[2].node.get_and_clear_pending_msg_events();
9157                 assert_eq!(events.len(), 1);
9158                 match events[0] {
9159                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9160                         _ => panic!("Unexpected event"),
9161                 }
9162
9163                 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
9164                 assert_eq!(c_txn.len(), 3);
9165                 assert_eq!(c_txn[0], c_txn[2]);
9166                 assert_eq!(commitment_tx[0], c_txn[1]);
9167                 check_spends!(c_txn[1], chan_2.3.clone());
9168                 check_spends!(c_txn[2], c_txn[1].clone());
9169                 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
9170                 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9171                 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
9172                 assert_eq!(c_txn[0].lock_time, 0); // Success tx
9173
9174                 // 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
9175                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
9176                 {
9177                         let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9178                         assert_eq!(b_txn.len(), 4);
9179                         assert_eq!(b_txn[0], b_txn[3]);
9180                         check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
9181                         check_spends!(b_txn[2], b_txn[1].clone()); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
9182                         assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9183                         assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
9184                         assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
9185                         check_spends!(b_txn[0], c_txn[1].clone()); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
9186                         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9187                         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
9188                         assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
9189                         b_txn.clear();
9190                 }
9191                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
9192                 check_added_monitors!(nodes[1], 1);
9193                 match msg_events[0] {
9194                         MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
9195                         _ => panic!("Unexpected event"),
9196                 }
9197                 match msg_events[1] {
9198                         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, .. } } => {
9199                                 assert!(update_add_htlcs.is_empty());
9200                                 assert!(update_fail_htlcs.is_empty());
9201                                 assert_eq!(update_fulfill_htlcs.len(), 1);
9202                                 assert!(update_fail_malformed_htlcs.is_empty());
9203                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
9204                         },
9205                         _ => panic!("Unexpected event"),
9206                 };
9207                 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
9208                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9209                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
9210                 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9211                 assert_eq!(b_txn.len(), 3);
9212                 check_spends!(b_txn[1], chan_1.3); // Local commitment tx, issued by ChannelManager
9213                 assert_eq!(b_txn[0], b_txn[2]); // HTLC-Success tx, issued by ChannelMonitor, * 2 due to block rescan
9214                 check_spends!(b_txn[0], commitment_tx[0].clone());
9215                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9216                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
9217                 assert_eq!(b_txn[2].lock_time, 0); // Success tx
9218                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
9219                 match msg_events[0] {
9220                         MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
9221                         _ => panic!("Unexpected event"),
9222                 }
9223         }
9224
9225         #[test]
9226         fn test_duplicate_payment_hash_one_failure_one_success() {
9227                 // Topology : A --> B --> C
9228                 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
9229                 let mut nodes = create_network(3);
9230
9231                 create_announced_chan_between_nodes(&nodes, 0, 1);
9232                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
9233
9234                 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
9235                 *nodes[0].network_payment_count.borrow_mut() -= 1;
9236                 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
9237
9238                 let commitment_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
9239                 assert_eq!(commitment_txn[0].input.len(), 1);
9240                 check_spends!(commitment_txn[0], chan_2.3.clone());
9241
9242                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9243                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
9244                 let htlc_timeout_tx;
9245                 { // Extract one of the two HTLC-Timeout transaction
9246                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9247                         assert_eq!(node_txn.len(), 7);
9248                         assert_eq!(node_txn[0], node_txn[5]);
9249                         assert_eq!(node_txn[1], node_txn[6]);
9250                         check_spends!(node_txn[0], commitment_txn[0].clone());
9251                         assert_eq!(node_txn[0].input.len(), 1);
9252                         check_spends!(node_txn[1], commitment_txn[0].clone());
9253                         assert_eq!(node_txn[1].input.len(), 1);
9254                         assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
9255                         check_spends!(node_txn[2], chan_2.3.clone());
9256                         check_spends!(node_txn[3], node_txn[2].clone());
9257                         check_spends!(node_txn[4], node_txn[2].clone());
9258                         htlc_timeout_tx = node_txn[1].clone();
9259                 }
9260
9261                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9262                 match events[0] {
9263                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9264                         _ => panic!("Unexepected event"),
9265                 }
9266
9267                 nodes[2].node.claim_funds(our_payment_preimage);
9268                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
9269                 check_added_monitors!(nodes[2], 2);
9270                 let events = nodes[2].node.get_and_clear_pending_msg_events();
9271                 match events[0] {
9272                         MessageSendEvent::UpdateHTLCs { .. } => {},
9273                         _ => panic!("Unexpected event"),
9274                 }
9275                 match events[1] {
9276                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9277                         _ => panic!("Unexepected event"),
9278                 }
9279                 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9280                 assert_eq!(htlc_success_txn.len(), 5);
9281                 check_spends!(htlc_success_txn[2], chan_2.3.clone());
9282                 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
9283                 assert_eq!(htlc_success_txn[0].input.len(), 1);
9284                 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9285                 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
9286                 assert_eq!(htlc_success_txn[1].input.len(), 1);
9287                 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9288                 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
9289                 check_spends!(htlc_success_txn[0], commitment_txn[0].clone());
9290                 check_spends!(htlc_success_txn[1], commitment_txn[0].clone());
9291
9292                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
9293                 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9294                 assert!(htlc_updates.update_add_htlcs.is_empty());
9295                 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
9296                 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
9297                 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
9298                 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
9299                 check_added_monitors!(nodes[1], 1);
9300
9301                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]).unwrap();
9302                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9303                 {
9304                         commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
9305                         let events = nodes[0].node.get_and_clear_pending_msg_events();
9306                         assert_eq!(events.len(), 1);
9307                         match events[0] {
9308                                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
9309                                 },
9310                                 _ => { panic!("Unexpected event"); }
9311                         }
9312                 }
9313                 let events = nodes[0].node.get_and_clear_pending_events();
9314                 match events[0] {
9315                         Event::PaymentFailed { ref payment_hash, .. } => {
9316                                 assert_eq!(*payment_hash, duplicate_payment_hash);
9317                         }
9318                         _ => panic!("Unexpected event"),
9319                 }
9320
9321                 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
9322                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
9323                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9324                 assert!(updates.update_add_htlcs.is_empty());
9325                 assert!(updates.update_fail_htlcs.is_empty());
9326                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
9327                 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
9328                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9329                 check_added_monitors!(nodes[1], 1);
9330
9331                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
9332                 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
9333
9334                 let events = nodes[0].node.get_and_clear_pending_events();
9335                 match events[0] {
9336                         Event::PaymentSent { ref payment_preimage } => {
9337                                 assert_eq!(*payment_preimage, our_payment_preimage);
9338                         }
9339                         _ => panic!("Unexpected event"),
9340                 }
9341         }
9342
9343         #[test]
9344         fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
9345                 let nodes = create_network(2);
9346
9347                 // Create some initial channels
9348                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9349
9350                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
9351                 let local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9352                 assert_eq!(local_txn[0].input.len(), 1);
9353                 check_spends!(local_txn[0], chan_1.3.clone());
9354
9355                 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
9356                 nodes[1].node.claim_funds(payment_preimage);
9357                 check_added_monitors!(nodes[1], 1);
9358                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9359                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
9360                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9361                 match events[0] {
9362                         MessageSendEvent::UpdateHTLCs { .. } => {},
9363                         _ => panic!("Unexpected event"),
9364                 }
9365                 match events[1] {
9366                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9367                         _ => panic!("Unexepected event"),
9368                 }
9369                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9370                 assert_eq!(node_txn[0].input.len(), 1);
9371                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9372                 check_spends!(node_txn[0], local_txn[0].clone());
9373
9374                 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
9375                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9376                 assert_eq!(spend_txn.len(), 2);
9377                 check_spends!(spend_txn[0], node_txn[0].clone());
9378                 check_spends!(spend_txn[1], node_txn[2].clone());
9379         }
9380
9381         #[test]
9382         fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
9383                 let nodes = create_network(2);
9384
9385                 // Create some initial channels
9386                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9387
9388                 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
9389                 let local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9390                 assert_eq!(local_txn[0].input.len(), 1);
9391                 check_spends!(local_txn[0], chan_1.3.clone());
9392
9393                 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
9394                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9395                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
9396                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9397                 match events[0] {
9398                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9399                         _ => panic!("Unexepected event"),
9400                 }
9401                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9402                 assert_eq!(node_txn[0].input.len(), 1);
9403                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9404                 check_spends!(node_txn[0], local_txn[0].clone());
9405
9406                 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
9407                 let spend_txn = check_spendable_outputs!(nodes[0], 1);
9408                 assert_eq!(spend_txn.len(), 8);
9409                 assert_eq!(spend_txn[0], spend_txn[2]);
9410                 assert_eq!(spend_txn[0], spend_txn[4]);
9411                 assert_eq!(spend_txn[0], spend_txn[6]);
9412                 assert_eq!(spend_txn[1], spend_txn[3]);
9413                 assert_eq!(spend_txn[1], spend_txn[5]);
9414                 assert_eq!(spend_txn[1], spend_txn[7]);
9415                 check_spends!(spend_txn[0], local_txn[0].clone());
9416                 check_spends!(spend_txn[1], node_txn[0].clone());
9417         }
9418
9419         #[test]
9420         fn test_static_output_closing_tx() {
9421                 let nodes = create_network(2);
9422
9423                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
9424
9425                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
9426                 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
9427
9428                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9429                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
9430                 let spend_txn = check_spendable_outputs!(nodes[0], 2);
9431                 assert_eq!(spend_txn.len(), 1);
9432                 check_spends!(spend_txn[0], closing_tx.clone());
9433
9434                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
9435                 let spend_txn = check_spendable_outputs!(nodes[1], 2);
9436                 assert_eq!(spend_txn.len(), 1);
9437                 check_spends!(spend_txn[0], closing_tx);
9438         }
9439
9440         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>)
9441                 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
9442                                         F2: FnMut(),
9443         {
9444                 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);
9445         }
9446
9447         // test_case
9448         // 0: node1 fail backward
9449         // 1: final node fail backward
9450         // 2: payment completed but the user reject the payment
9451         // 3: final node fail backward (but tamper onion payloads from node0)
9452         // 100: trigger error in the intermediate node and tamper returnning fail_htlc
9453         // 200: trigger error in the final node and tamper returnning fail_htlc
9454         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>)
9455                 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
9456                                         F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
9457                                         F3: FnMut(),
9458         {
9459                 use ln::msgs::HTLCFailChannelUpdate;
9460
9461                 // reset block height
9462                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9463                 for ix in 0..nodes.len() {
9464                         nodes[ix].chain_monitor.block_connected_checked(&header, 1, &Vec::new()[..], &[0; 0]);
9465                 }
9466
9467                 macro_rules! expect_event {
9468                         ($node: expr, $event_type: path) => {{
9469                                 let events = $node.node.get_and_clear_pending_events();
9470                                 assert_eq!(events.len(), 1);
9471                                 match events[0] {
9472                                         $event_type { .. } => {},
9473                                         _ => panic!("Unexpected event"),
9474                                 }
9475                         }}
9476                 }
9477
9478                 macro_rules! expect_htlc_forward {
9479                         ($node: expr) => {{
9480                                 expect_event!($node, Event::PendingHTLCsForwardable);
9481                                 $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
9482                                 $node.node.process_pending_htlc_forwards();
9483                         }}
9484                 }
9485
9486                 // 0 ~~> 2 send payment
9487                 nodes[0].node.send_payment(route.clone(), payment_hash.clone()).unwrap();
9488                 check_added_monitors!(nodes[0], 1);
9489                 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
9490                 // temper update_add (0 => 1)
9491                 let mut update_add_0 = update_0.update_add_htlcs[0].clone();
9492                 if test_case == 0 || test_case == 3 || test_case == 100 {
9493                         callback_msg(&mut update_add_0);
9494                         callback_node();
9495                 }
9496                 // 0 => 1 update_add & CS
9497                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0).unwrap();
9498                 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
9499
9500                 let update_1_0 = match test_case {
9501                         0|100 => { // intermediate node failure; fail backward to 0
9502                                 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9503                                 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));
9504                                 update_1_0
9505                         },
9506                         1|2|3|200 => { // final node failure; forwarding to 2
9507                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9508                                 // forwarding on 1
9509                                 if test_case != 200 {
9510                                         callback_node();
9511                                 }
9512                                 expect_htlc_forward!(&nodes[1]);
9513
9514                                 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
9515                                 check_added_monitors!(&nodes[1], 1);
9516                                 assert_eq!(update_1.update_add_htlcs.len(), 1);
9517                                 // tamper update_add (1 => 2)
9518                                 let mut update_add_1 = update_1.update_add_htlcs[0].clone();
9519                                 if test_case != 3 && test_case != 200 {
9520                                         callback_msg(&mut update_add_1);
9521                                 }
9522
9523                                 // 1 => 2
9524                                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1).unwrap();
9525                                 commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
9526
9527                                 if test_case == 2 || test_case == 200 {
9528                                         expect_htlc_forward!(&nodes[2]);
9529                                         expect_event!(&nodes[2], Event::PaymentReceived);
9530                                         callback_node();
9531                                 }
9532
9533                                 let update_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9534                                 if test_case == 2 || test_case == 200 {
9535                                         check_added_monitors!(&nodes[2], 1);
9536                                 }
9537                                 assert!(update_2_1.update_fail_htlcs.len() == 1);
9538
9539                                 let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
9540                                 if test_case == 200 {
9541                                         callback_fail(&mut fail_msg);
9542                                 }
9543
9544                                 // 2 => 1
9545                                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg).unwrap();
9546                                 commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true, true);
9547
9548                                 // backward fail on 1
9549                                 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9550                                 assert!(update_1_0.update_fail_htlcs.len() == 1);
9551                                 update_1_0
9552                         },
9553                         _ => unreachable!(),
9554                 };
9555
9556                 // 1 => 0 commitment_signed_dance
9557                 if update_1_0.update_fail_htlcs.len() > 0 {
9558                         let mut fail_msg = update_1_0.update_fail_htlcs[0].clone();
9559                         if test_case == 100 {
9560                                 callback_fail(&mut fail_msg);
9561                         }
9562                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg).unwrap();
9563                 } else {
9564                         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]).unwrap();
9565                 };
9566
9567                 commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
9568
9569                 let events = nodes[0].node.get_and_clear_pending_events();
9570                 assert_eq!(events.len(), 1);
9571                 if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code } = &events[0] {
9572                         assert_eq!(*rejected_by_dest, !expected_retryable);
9573                         assert_eq!(*error_code, expected_error_code);
9574                 } else {
9575                         panic!("Uexpected event");
9576                 }
9577
9578                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9579                 if expected_channel_update.is_some() {
9580                         assert_eq!(events.len(), 1);
9581                         match events[0] {
9582                                 MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
9583                                         match update {
9584                                                 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {
9585                                                         if let HTLCFailChannelUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
9586                                                                 panic!("channel_update not found!");
9587                                                         }
9588                                                 },
9589                                                 &HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
9590                                                         if let HTLCFailChannelUpdate::ChannelClosed { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
9591                                                                 assert!(*short_channel_id == *expected_short_channel_id);
9592                                                                 assert!(*is_permanent == *expected_is_permanent);
9593                                                         } else {
9594                                                                 panic!("Unexpected message event");
9595                                                         }
9596                                                 },
9597                                                 &HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
9598                                                         if let HTLCFailChannelUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
9599                                                                 assert!(*node_id == *expected_node_id);
9600                                                                 assert!(*is_permanent == *expected_is_permanent);
9601                                                         } else {
9602                                                                 panic!("Unexpected message event");
9603                                                         }
9604                                                 },
9605                                         }
9606                                 },
9607                                 _ => panic!("Unexpected message event"),
9608                         }
9609                 } else {
9610                         assert_eq!(events.len(), 0);
9611                 }
9612         }
9613
9614         impl msgs::ChannelUpdate {
9615                 fn dummy() -> msgs::ChannelUpdate {
9616                         use secp256k1::ffi::Signature as FFISignature;
9617                         use secp256k1::Signature;
9618                         msgs::ChannelUpdate {
9619                                 signature: Signature::from(FFISignature::new()),
9620                                 contents: msgs::UnsignedChannelUpdate {
9621                                         chain_hash: Sha256dHash::from_data(&vec![0u8][..]),
9622                                         short_channel_id: 0,
9623                                         timestamp: 0,
9624                                         flags: 0,
9625                                         cltv_expiry_delta: 0,
9626                                         htlc_minimum_msat: 0,
9627                                         fee_base_msat: 0,
9628                                         fee_proportional_millionths: 0,
9629                                         excess_data: vec![],
9630                                 }
9631                         }
9632                 }
9633         }
9634
9635         #[test]
9636         fn test_onion_failure() {
9637                 use ln::msgs::ChannelUpdate;
9638                 use ln::channelmanager::CLTV_FAR_FAR_AWAY;
9639                 use secp256k1;
9640
9641                 const BADONION: u16 = 0x8000;
9642                 const PERM: u16 = 0x4000;
9643                 const NODE: u16 = 0x2000;
9644                 const UPDATE: u16 = 0x1000;
9645
9646                 let mut nodes = create_network(3);
9647                 for node in nodes.iter() {
9648                         *node.keys_manager.override_session_priv.lock().unwrap() = Some(SecretKey::from_slice(&Secp256k1::without_caps(), &[3; 32]).unwrap());
9649                 }
9650                 let channels = [create_announced_chan_between_nodes(&nodes, 0, 1), create_announced_chan_between_nodes(&nodes, 1, 2)];
9651                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
9652                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap();
9653                 // positve case
9654                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000);
9655
9656                 // intermediate node failure
9657                 run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, |msg| {
9658                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9659                         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
9660                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9661                         let (mut onion_payloads, _htlc_msat, _htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height).unwrap();
9662                         onion_payloads[0].realm = 3;
9663                         msg.onion_routing_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
9664                 }, ||{}, 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
9665
9666                 // final node failure
9667                 run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, |msg| {
9668                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9669                         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
9670                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9671                         let (mut onion_payloads, _htlc_msat, _htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height).unwrap();
9672                         onion_payloads[1].realm = 3;
9673                         msg.onion_routing_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
9674                 }, ||{}, false, Some(PERM|1), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
9675
9676                 // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
9677                 // receiving simulated fail messages
9678                 // intermediate node failure
9679                 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
9680                         // trigger error
9681                         msg.amount_msat -= 1;
9682                 }, |msg| {
9683                         // and tamper returing error message
9684                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9685                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9686                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], NODE|2, &[0;0]);
9687                 }, ||{}, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: false}));
9688
9689                 // final node failure
9690                 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
9691                         // and tamper returing error message
9692                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9693                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9694                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], NODE|2, &[0;0]);
9695                 }, ||{
9696                         nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
9697                 }, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: false}));
9698
9699                 // intermediate node failure
9700                 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
9701                         msg.amount_msat -= 1;
9702                 }, |msg| {
9703                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9704                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9705                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|2, &[0;0]);
9706                 }, ||{}, true, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
9707
9708                 // final node failure
9709                 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
9710                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9711                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9712                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|2, &[0;0]);
9713                 }, ||{
9714                         nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
9715                 }, false, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
9716
9717                 // intermediate node failure
9718                 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
9719                         msg.amount_msat -= 1;
9720                 }, |msg| {
9721                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9722                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9723                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|3, &[0;0]);
9724                 }, ||{
9725                         nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
9726                 }, true, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
9727
9728                 // final node failure
9729                 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
9730                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9731                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9732                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|3, &[0;0]);
9733                 }, ||{
9734                         nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
9735                 }, false, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
9736
9737                 run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
9738                         Some(BADONION|PERM|4), None);
9739
9740                 run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
9741                         Some(BADONION|PERM|5), None);
9742
9743                 run_onion_failure_test("invalid_onion_key", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.public_key = Err(secp256k1::Error::InvalidPublicKey);}, ||{}, true,
9744                         Some(BADONION|PERM|6), None);
9745
9746                 run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
9747                         msg.amount_msat -= 1;
9748                 }, |msg| {
9749                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9750                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9751                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], UPDATE|7, &ChannelUpdate::dummy().encode_with_len()[..]);
9752                 }, ||{}, true, Some(UPDATE|7), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
9753
9754                 run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
9755                         msg.amount_msat -= 1;
9756                 }, |msg| {
9757                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9758                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9759                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|8, &[0;0]);
9760                         // short_channel_id from the processing node
9761                 }, ||{}, true, Some(PERM|8), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
9762
9763                 run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
9764                         msg.amount_msat -= 1;
9765                 }, |msg| {
9766                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9767                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9768                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|9, &[0;0]);
9769                         // short_channel_id from the processing node
9770                 }, ||{}, true, Some(PERM|9), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
9771
9772                 let mut bogus_route = route.clone();
9773                 bogus_route.hops[1].short_channel_id -= 1;
9774                 run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(PERM|10),
9775                   Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: bogus_route.hops[1].short_channel_id, is_permanent:true}));
9776
9777                 let amt_to_forward = nodes[1].node.channel_state.lock().unwrap().by_id.get(&channels[1].2).unwrap().get_their_htlc_minimum_msat() - 1;
9778                 let mut bogus_route = route.clone();
9779                 let route_len = bogus_route.hops.len();
9780                 bogus_route.hops[route_len-1].fee_msat = amt_to_forward;
9781                 run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(UPDATE|11), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
9782
9783                 //TODO: with new config API, we will be able to generate both valid and
9784                 //invalid channel_update cases.
9785                 run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, |msg| {
9786                         msg.amount_msat -= 1;
9787                 }, || {}, true, Some(UPDATE|12), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
9788
9789                 run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, |msg| {
9790                         // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
9791                         msg.cltv_expiry -= 1;
9792                 }, || {}, true, Some(UPDATE|13), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
9793
9794                 run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, |msg| {
9795                         let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - HTLC_FAIL_TIMEOUT_BLOCKS + 1;
9796                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9797                         nodes[1].chain_monitor.block_connected_checked(&header, height, &Vec::new()[..], &[0; 0]);
9798                 }, ||{}, true, Some(UPDATE|14), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
9799
9800                 run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, |_| {}, || {
9801                         nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
9802                 }, false, Some(PERM|15), None);
9803
9804                 run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, |msg| {
9805                         let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - HTLC_FAIL_TIMEOUT_BLOCKS + 1;
9806                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9807                         nodes[2].chain_monitor.block_connected_checked(&header, height, &Vec::new()[..], &[0; 0]);
9808                 }, || {}, true, Some(17), None);
9809
9810                 run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, |_| {}, || {
9811                         for (_, mut pending_forwards) in nodes[1].node.channel_state.lock().unwrap().borrow_parts().forward_htlcs.iter_mut() {
9812                                 for f in pending_forwards.iter_mut() {
9813                                         f.forward_info.outgoing_cltv_value += 1;
9814                                 }
9815                         }
9816                 }, true, Some(18), None);
9817
9818                 run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, |_| {}, || {
9819                         // violate amt_to_forward > msg.amount_msat
9820                         for (_, mut pending_forwards) in nodes[1].node.channel_state.lock().unwrap().borrow_parts().forward_htlcs.iter_mut() {
9821                                 for f in pending_forwards.iter_mut() {
9822                                         f.forward_info.amt_to_forward -= 1;
9823                                 }
9824                         }
9825                 }, true, Some(19), None);
9826
9827                 run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, |_| {}, || {
9828                         // disconnect event to the channel between nodes[1] ~ nodes[2]
9829                         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9830                         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9831                 }, true, Some(UPDATE|20), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
9832                 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9833
9834                 run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, |msg| {
9835                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9836                         let mut route = route.clone();
9837                         let height = 1;
9838                         route.hops[1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.hops[0].cltv_expiry_delta + 1;
9839                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9840                         let (onion_payloads, _, htlc_cltv) = ChannelManager::build_onion_payloads(&route, height).unwrap();
9841                         let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
9842                         msg.cltv_expiry = htlc_cltv;
9843                         msg.onion_routing_packet = onion_packet;
9844                 }, ||{}, true, Some(21), None);
9845         }
9846 }