Swap an if let for a match and add some TODO
[rust-lightning] / src / ln / channelmanager.rs
1 //! The top-level channel management and payment tracking stuff lives here.
2 //!
3 //! The ChannelManager is the main chunk of logic implementing the lightning protocol and is
4 //! responsible for tracking which channels are open, HTLCs are in flight and reestablishing those
5 //! upon reconnect to the relevant peer(s).
6 //!
7 //! It does not manage routing logic (see ln::router for that) nor does it manage constructing
8 //! on-chain transactions (it only monitors the chain to watch for any force-closes that might
9 //! imply it needs to fail HTLCs/payments/channels it manages).
10
11 use bitcoin::blockdata::block::BlockHeader;
12 use bitcoin::blockdata::transaction::Transaction;
13 use bitcoin::blockdata::constants::genesis_block;
14 use bitcoin::network::constants::Network;
15 use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
16
17 use secp256k1::key::{SecretKey,PublicKey};
18 use secp256k1::{Secp256k1,Message};
19 use secp256k1::ecdh::SharedSecret;
20 use secp256k1;
21
22 use chain::chaininterface::{BroadcasterInterface,ChainListener,ChainWatchInterface,FeeEstimator};
23 use chain::transaction::OutPoint;
24 use ln::channel::{Channel, ChannelError};
25 use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, ManyChannelMonitor, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, HTLC_FAIL_ANTI_REORG_DELAY};
26 use ln::router::{Route,RouteHop};
27 use ln::msgs;
28 use ln::msgs::{ChannelMessageHandler, DecodeError, HandleError};
29 use chain::keysinterface::KeysInterface;
30 use util::config::UserConfig;
31 use util::{byte_utils, events, internal_traits, rng};
32 use util::sha2::Sha256;
33 use util::ser::{Readable, ReadableArgs, Writeable, Writer};
34 use util::chacha20poly1305rfc::ChaCha20;
35 use util::logger::Logger;
36 use util::errors::APIError;
37
38 use crypto;
39 use crypto::mac::{Mac,MacResult};
40 use crypto::hmac::Hmac;
41 use crypto::digest::Digest;
42 use crypto::symmetriccipher::SynchronousStreamCipher;
43
44 use std::{cmp, ptr, mem};
45 use std::collections::{HashMap, hash_map, HashSet};
46 use std::io::Cursor;
47 use std::sync::{Arc, Mutex, MutexGuard, RwLock};
48 use std::sync::atomic::{AtomicUsize, Ordering};
49 use std::time::{Instant,Duration};
50
51 /// We hold various information about HTLC relay in the HTLC objects in Channel itself:
52 ///
53 /// Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
54 /// forward the HTLC with information it will give back to us when it does so, or if it should Fail
55 /// the HTLC with the relevant message for the Channel to handle giving to the remote peer.
56 ///
57 /// When a Channel forwards an HTLC to its peer, it will give us back the PendingForwardHTLCInfo
58 /// which we will use to construct an outbound HTLC, with a relevant HTLCSource::PreviousHopData
59 /// filled in to indicate where it came from (which we can use to either fail-backwards or fulfill
60 /// the HTLC backwards along the relevant path).
61 /// Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
62 /// our payment, which we can use to decode errors or inform the user that the payment was sent.
63 mod channel_held_info {
64         use ln::msgs;
65         use ln::router::Route;
66         use ln::channelmanager::PaymentHash;
67         use secp256k1::key::SecretKey;
68
69         /// Stores the info we will need to send when we want to forward an HTLC onwards
70         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
71         pub struct PendingForwardHTLCInfo {
72                 pub(super) onion_packet: Option<msgs::OnionPacket>,
73                 pub(super) incoming_shared_secret: [u8; 32],
74                 pub(super) payment_hash: PaymentHash,
75                 pub(super) short_channel_id: u64,
76                 pub(super) amt_to_forward: u64,
77                 pub(super) outgoing_cltv_value: u32,
78         }
79
80         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
81         pub enum HTLCFailureMsg {
82                 Relay(msgs::UpdateFailHTLC),
83                 Malformed(msgs::UpdateFailMalformedHTLC),
84         }
85
86         /// Stores whether we can't forward an HTLC or relevant forwarding info
87         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
88         pub enum PendingHTLCStatus {
89                 Forward(PendingForwardHTLCInfo),
90                 Fail(HTLCFailureMsg),
91         }
92
93         /// Tracks the inbound corresponding to an outbound HTLC
94         #[derive(Clone, PartialEq)]
95         pub struct HTLCPreviousHopData {
96                 pub(super) short_channel_id: u64,
97                 pub(super) htlc_id: u64,
98                 pub(super) incoming_packet_shared_secret: [u8; 32],
99         }
100
101         /// Tracks the inbound corresponding to an outbound HTLC
102         #[derive(Clone, PartialEq)]
103         pub enum HTLCSource {
104                 PreviousHopData(HTLCPreviousHopData),
105                 OutboundRoute {
106                         route: Route,
107                         session_priv: SecretKey,
108                         /// Technically we can recalculate this from the route, but we cache it here to avoid
109                         /// doing a double-pass on route when we get a failure back
110                         first_hop_htlc_msat: u64,
111                 },
112         }
113         #[cfg(test)]
114         impl HTLCSource {
115                 pub fn dummy() -> Self {
116                         HTLCSource::OutboundRoute {
117                                 route: Route { hops: Vec::new() },
118                                 session_priv: SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[1; 32]).unwrap(),
119                                 first_hop_htlc_msat: 0,
120                         }
121                 }
122         }
123
124         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
125         pub(crate) enum HTLCFailReason {
126                 ErrorPacket {
127                         err: msgs::OnionErrorPacket,
128                 },
129                 Reason {
130                         failure_code: u16,
131                         data: Vec<u8>,
132                 }
133         }
134 }
135 pub(super) use self::channel_held_info::*;
136
137 /// payment_hash type, use to cross-lock hop
138 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
139 pub struct PaymentHash(pub [u8;32]);
140 /// payment_preimage type, use to route payment between hop
141 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
142 pub struct PaymentPreimage(pub [u8;32]);
143
144 type ShutdownResult = (Vec<Transaction>, Vec<(HTLCSource, PaymentHash)>);
145
146 /// Error type returned across the channel_state mutex boundary. When an Err is generated for a
147 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
148 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
149 /// channel_state lock. We then return the set of things that need to be done outside the lock in
150 /// this struct and call handle_error!() on it.
151
152 struct MsgHandleErrInternal {
153         err: msgs::HandleError,
154         shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
155 }
156 impl MsgHandleErrInternal {
157         #[inline]
158         fn send_err_msg_no_close(err: &'static str, channel_id: [u8; 32]) -> Self {
159                 Self {
160                         err: HandleError {
161                                 err,
162                                 action: Some(msgs::ErrorAction::SendErrorMessage {
163                                         msg: msgs::ErrorMessage {
164                                                 channel_id,
165                                                 data: err.to_string()
166                                         },
167                                 }),
168                         },
169                         shutdown_finish: None,
170                 }
171         }
172         #[inline]
173         fn from_no_close(err: msgs::HandleError) -> Self {
174                 Self { err, shutdown_finish: None }
175         }
176         #[inline]
177         fn from_finish_shutdown(err: &'static str, channel_id: [u8; 32], shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
178                 Self {
179                         err: HandleError {
180                                 err,
181                                 action: Some(msgs::ErrorAction::SendErrorMessage {
182                                         msg: msgs::ErrorMessage {
183                                                 channel_id,
184                                                 data: err.to_string()
185                                         },
186                                 }),
187                         },
188                         shutdown_finish: Some((shutdown_res, channel_update)),
189                 }
190         }
191         #[inline]
192         fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
193                 Self {
194                         err: match err {
195                                 ChannelError::Ignore(msg) => HandleError {
196                                         err: msg,
197                                         action: Some(msgs::ErrorAction::IgnoreError),
198                                 },
199                                 ChannelError::Close(msg) => HandleError {
200                                         err: msg,
201                                         action: Some(msgs::ErrorAction::SendErrorMessage {
202                                                 msg: msgs::ErrorMessage {
203                                                         channel_id,
204                                                         data: msg.to_string()
205                                                 },
206                                         }),
207                                 },
208                         },
209                         shutdown_finish: None,
210                 }
211         }
212 }
213
214 /// Pass to fail_htlc_backwwards to indicate the reason to fail the payment
215 /// after a PaymentReceived event.
216 #[derive(PartialEq)]
217 pub enum PaymentFailReason {
218         /// Indicate the preimage for payment_hash is not known after a PaymentReceived event
219         PreimageUnknown,
220         /// Indicate the payment amount is incorrect ( received is < expected or > 2*expected ) after a PaymentReceived event
221         AmountMismatch,
222 }
223
224 /// We hold back HTLCs we intend to relay for a random interval in the range (this, 5*this). This
225 /// provides some limited amount of privacy. Ideally this would range from somewhere like 1 second
226 /// to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly. We could
227 /// probably increase this significantly.
228 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
229
230 struct HTLCForwardInfo {
231         prev_short_channel_id: u64,
232         prev_htlc_id: u64,
233         forward_info: PendingForwardHTLCInfo,
234 }
235
236 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
237 /// be sent in the order they appear in the return value, however sometimes the order needs to be
238 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
239 /// they were originally sent). In those cases, this enum is also returned.
240 #[derive(Clone, PartialEq)]
241 pub(super) enum RAACommitmentOrder {
242         /// Send the CommitmentUpdate messages first
243         CommitmentFirst,
244         /// Send the RevokeAndACK message first
245         RevokeAndACKFirst,
246 }
247
248 struct ChannelHolder {
249         by_id: HashMap<[u8; 32], Channel>,
250         short_to_id: HashMap<u64, [u8; 32]>,
251         next_forward: Instant,
252         /// short channel id -> forward infos. Key of 0 means payments received
253         /// Note that while this is held in the same mutex as the channels themselves, no consistency
254         /// guarantees are made about there existing a channel with the short id here, nor the short
255         /// ids in the PendingForwardHTLCInfo!
256         forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
257         /// Note that while this is held in the same mutex as the channels themselves, no consistency
258         /// guarantees are made about the channels given here actually existing anymore by the time you
259         /// go to read them!
260         claimable_htlcs: HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
261         /// Messages to send to peers - pushed to in the same lock that they are generated in (except
262         /// for broadcast messages, where ordering isn't as strict).
263         pending_msg_events: Vec<events::MessageSendEvent>,
264 }
265 struct MutChannelHolder<'a> {
266         by_id: &'a mut HashMap<[u8; 32], Channel>,
267         short_to_id: &'a mut HashMap<u64, [u8; 32]>,
268         next_forward: &'a mut Instant,
269         forward_htlcs: &'a mut HashMap<u64, Vec<HTLCForwardInfo>>,
270         claimable_htlcs: &'a mut HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
271         pending_msg_events: &'a mut Vec<events::MessageSendEvent>,
272 }
273 impl ChannelHolder {
274         fn borrow_parts(&mut self) -> MutChannelHolder {
275                 MutChannelHolder {
276                         by_id: &mut self.by_id,
277                         short_to_id: &mut self.short_to_id,
278                         next_forward: &mut self.next_forward,
279                         forward_htlcs: &mut self.forward_htlcs,
280                         claimable_htlcs: &mut self.claimable_htlcs,
281                         pending_msg_events: &mut self.pending_msg_events,
282                 }
283         }
284 }
285
286 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
287 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
288
289 /// Manager which keeps track of a number of channels and sends messages to the appropriate
290 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
291 ///
292 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
293 /// to individual Channels.
294 ///
295 /// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
296 /// all peers during write/read (though does not modify this instance, only the instance being
297 /// serialized). This will result in any channels which have not yet exchanged funding_created (ie
298 /// called funding_transaction_generated for outbound channels).
299 ///
300 /// Note that you can be a bit lazier about writing out ChannelManager than you can be with
301 /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
302 /// returning from ManyChannelMonitor::add_update_monitor, with ChannelManagers, writing updates
303 /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during
304 /// the serialization process). If the deserialized version is out-of-date compared to the
305 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
306 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
307 ///
308 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelManager), which
309 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
310 /// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
311 /// block_connected() to step towards your best block) upon deserialization before using the
312 /// object!
313 pub struct ChannelManager {
314         default_configuration: UserConfig,
315         genesis_hash: Sha256dHash,
316         fee_estimator: Arc<FeeEstimator>,
317         monitor: Arc<ManyChannelMonitor>,
318         chain_monitor: Arc<ChainWatchInterface>,
319         tx_broadcaster: Arc<BroadcasterInterface>,
320
321         latest_block_height: AtomicUsize,
322         last_block_hash: Mutex<Sha256dHash>,
323         secp_ctx: Secp256k1<secp256k1::All>,
324
325         channel_state: Mutex<ChannelHolder>,
326         our_network_key: SecretKey,
327
328         pending_events: Mutex<Vec<events::Event>>,
329         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
330         /// Essentially just when we're serializing ourselves out.
331         /// Taken first everywhere where we are making changes before any other locks.
332         total_consistency_lock: RwLock<()>,
333
334         keys_manager: Arc<KeysInterface>,
335
336         logger: Arc<Logger>,
337 }
338
339 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
340 /// HTLC's CLTV. This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
341 /// ie the node we forwarded the payment on to should always have enough room to reliably time out
342 /// the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
343 /// CLTV_CLAIM_BUFFER point (we static assert that its at least 3 blocks more).
344 const CLTV_EXPIRY_DELTA: u16 = 6 * 12; //TODO?
345 const CLTV_FAR_FAR_AWAY: u32 = 6 * 24 * 7; //TODO?
346
347 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + 2*HTLC_FAIL_TIMEOUT_BLOCKS +
348 // HTLC_FAIL_ANTI_REORG_DELAY, ie that if the next-hop peer fails the HTLC within
349 // HTLC_FAIL_TIMEOUT_BLOCKS then we'll still have HTLC_FAIL_TIMEOUT_BLOCKS left to fail it
350 // backwards ourselves before hitting the CLTV_CLAIM_BUFFER point and failing the channel
351 // on-chain to time out the HTLC.
352 #[deny(const_err)]
353 #[allow(dead_code)]
354 const CHECK_CLTV_EXPIRY_SANITY: u32 = CLTV_EXPIRY_DELTA as u32 - 2*HTLC_FAIL_TIMEOUT_BLOCKS - CLTV_CLAIM_BUFFER - HTLC_FAIL_ANTI_REORG_DELAY;
355
356 // Check for ability of an attacker to make us fail on-chain by delaying inbound claim. See
357 // ChannelMontior::would_broadcast_at_height for a description of why this is needed.
358 #[deny(const_err)]
359 #[allow(dead_code)]
360 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = CLTV_EXPIRY_DELTA as u32 - HTLC_FAIL_TIMEOUT_BLOCKS - 2*CLTV_CLAIM_BUFFER;
361
362 macro_rules! secp_call {
363         ( $res: expr, $err: expr ) => {
364                 match $res {
365                         Ok(key) => key,
366                         Err(_) => return Err($err),
367                 }
368         };
369 }
370
371 struct OnionKeys {
372         #[cfg(test)]
373         shared_secret: SharedSecret,
374         #[cfg(test)]
375         blinding_factor: [u8; 32],
376         ephemeral_pubkey: PublicKey,
377         rho: [u8; 32],
378         mu: [u8; 32],
379 }
380
381 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
382 pub struct ChannelDetails {
383         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
384         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
385         /// Note that this means this value is *not* persistent - it can change once during the
386         /// lifetime of the channel.
387         pub channel_id: [u8; 32],
388         /// The position of the funding transaction in the chain. None if the funding transaction has
389         /// not yet been confirmed and the channel fully opened.
390         pub short_channel_id: Option<u64>,
391         /// The node_id of our counterparty
392         pub remote_network_id: PublicKey,
393         /// The value, in satoshis, of this channel as appears in the funding output
394         pub channel_value_satoshis: u64,
395         /// The user_id passed in to create_channel, or 0 if the channel was inbound.
396         pub user_id: u64,
397 }
398
399 macro_rules! handle_error {
400         ($self: ident, $internal: expr, $their_node_id: expr) => {
401                 match $internal {
402                         Ok(msg) => Ok(msg),
403                         Err(MsgHandleErrInternal { err, shutdown_finish }) => {
404                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
405                                         $self.finish_force_close_channel(shutdown_res);
406                                         if let Some(update) = update_option {
407                                                 let mut channel_state = $self.channel_state.lock().unwrap();
408                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
409                                                         msg: update
410                                                 });
411                                         }
412                                 }
413                                 Err(err)
414                         },
415                 }
416         }
417 }
418
419 macro_rules! break_chan_entry {
420         ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
421                 match $res {
422                         Ok(res) => res,
423                         Err(ChannelError::Ignore(msg)) => {
424                                 break Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
425                         },
426                         Err(ChannelError::Close(msg)) => {
427                                 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
428                                 let (channel_id, mut chan) = $entry.remove_entry();
429                                 if let Some(short_id) = chan.get_short_channel_id() {
430                                         $channel_state.short_to_id.remove(&short_id);
431                                 }
432                                 break Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
433                         },
434                 }
435         }
436 }
437
438 macro_rules! try_chan_entry {
439         ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
440                 match $res {
441                         Ok(res) => res,
442                         Err(ChannelError::Ignore(msg)) => {
443                                 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
444                         },
445                         Err(ChannelError::Close(msg)) => {
446                                 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
447                                 let (channel_id, mut chan) = $entry.remove_entry();
448                                 if let Some(short_id) = chan.get_short_channel_id() {
449                                         $channel_state.short_to_id.remove(&short_id);
450                                 }
451                                 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
452                         },
453                 }
454         }
455 }
456
457 macro_rules! return_monitor_err {
458         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
459                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new())
460         };
461         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $raa_first_dropped_cs: expr) => {
462                 if $action_type != RAACommitmentOrder::RevokeAndACKFirst { panic!("Bad return_monitor_err call!"); }
463                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new(), $raa_first_dropped_cs)
464         };
465         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr) => {
466                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, $failed_forwards, $failed_fails, false)
467         };
468         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr, $raa_first_dropped_cs: expr) => {
469                 match $err {
470                         ChannelMonitorUpdateErr::PermanentFailure => {
471                                 let (channel_id, mut chan) = $entry.remove_entry();
472                                 if let Some(short_id) = chan.get_short_channel_id() {
473                                         $channel_state.short_to_id.remove(&short_id);
474                                 }
475                                 // TODO: $failed_fails is dropped here, which will cause other channels to hit the
476                                 // chain in a confused state! We need to move them into the ChannelMonitor which
477                                 // will be responsible for failing backwards once things confirm on-chain.
478                                 // It's ok that we drop $failed_forwards here - at this point we'd rather they
479                                 // broadcast HTLC-Timeout and pay the associated fees to get their funds back than
480                                 // us bother trying to claim it just to forward on to another peer. If we're
481                                 // splitting hairs we'd prefer to claim payments that were to us, but we haven't
482                                 // given up the preimage yet, so might as well just wait until the payment is
483                                 // retried, avoiding the on-chain fees.
484                                 return Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
485                         },
486                         ChannelMonitorUpdateErr::TemporaryFailure => {
487                                 $entry.get_mut().monitor_update_failed($action_type, $failed_forwards, $failed_fails, $raa_first_dropped_cs);
488                                 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore("Failed to update ChannelMonitor"), *$entry.key()));
489                         },
490                 }
491         }
492 }
493
494 // Does not break in case of TemporaryFailure!
495 macro_rules! maybe_break_monitor_err {
496         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
497                 match $err {
498                         ChannelMonitorUpdateErr::PermanentFailure => {
499                                 let (channel_id, mut chan) = $entry.remove_entry();
500                                 if let Some(short_id) = chan.get_short_channel_id() {
501                                         $channel_state.short_to_id.remove(&short_id);
502                                 }
503                                 break Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
504                         },
505                         ChannelMonitorUpdateErr::TemporaryFailure => {
506                                 $entry.get_mut().monitor_update_failed($action_type, Vec::new(), Vec::new(), false);
507                         },
508                 }
509         }
510 }
511
512 impl ChannelManager {
513         /// Constructs a new ChannelManager to hold several channels and route between them.
514         ///
515         /// This is the main "logic hub" for all channel-related actions, and implements
516         /// ChannelMessageHandler.
517         ///
518         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
519         ///
520         /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
521         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> {
522                 let secp_ctx = Secp256k1::new();
523
524                 let res = Arc::new(ChannelManager {
525                         default_configuration: config.clone(),
526                         genesis_hash: genesis_block(network).header.bitcoin_hash(),
527                         fee_estimator: feeest.clone(),
528                         monitor: monitor.clone(),
529                         chain_monitor,
530                         tx_broadcaster,
531
532                         latest_block_height: AtomicUsize::new(0), //TODO: Get an init value
533                         last_block_hash: Mutex::new(Default::default()),
534                         secp_ctx,
535
536                         channel_state: Mutex::new(ChannelHolder{
537                                 by_id: HashMap::new(),
538                                 short_to_id: HashMap::new(),
539                                 next_forward: Instant::now(),
540                                 forward_htlcs: HashMap::new(),
541                                 claimable_htlcs: HashMap::new(),
542                                 pending_msg_events: Vec::new(),
543                         }),
544                         our_network_key: keys_manager.get_node_secret(),
545
546                         pending_events: Mutex::new(Vec::new()),
547                         total_consistency_lock: RwLock::new(()),
548
549                         keys_manager,
550
551                         logger,
552                 });
553                 let weak_res = Arc::downgrade(&res);
554                 res.chain_monitor.register_listener(weak_res);
555                 Ok(res)
556         }
557
558         /// Creates a new outbound channel to the given remote node and with the given value.
559         ///
560         /// user_id will be provided back as user_channel_id in FundingGenerationReady and
561         /// FundingBroadcastSafe events to allow tracking of which events correspond with which
562         /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
563         /// may wish to avoid using 0 for user_id here.
564         ///
565         /// If successful, will generate a SendOpenChannel message event, so you should probably poll
566         /// PeerManager::process_events afterwards.
567         ///
568         /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
569         /// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
570         pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64) -> Result<(), APIError> {
571                 if channel_value_satoshis < 1000 {
572                         return Err(APIError::APIMisuseError { err: "channel_value must be at least 1000 satoshis" });
573                 }
574
575                 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)?;
576                 let res = channel.get_open_channel(self.genesis_hash.clone(), &*self.fee_estimator);
577
578                 let _ = self.total_consistency_lock.read().unwrap();
579                 let mut channel_state = self.channel_state.lock().unwrap();
580                 match channel_state.by_id.entry(channel.channel_id()) {
581                         hash_map::Entry::Occupied(_) => {
582                                 if cfg!(feature = "fuzztarget") {
583                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG" });
584                                 } else {
585                                         panic!("RNG is bad???");
586                                 }
587                         },
588                         hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
589                 }
590                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
591                         node_id: their_network_key,
592                         msg: res,
593                 });
594                 Ok(())
595         }
596
597         /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
598         /// more information.
599         pub fn list_channels(&self) -> Vec<ChannelDetails> {
600                 let channel_state = self.channel_state.lock().unwrap();
601                 let mut res = Vec::with_capacity(channel_state.by_id.len());
602                 for (channel_id, channel) in channel_state.by_id.iter() {
603                         res.push(ChannelDetails {
604                                 channel_id: (*channel_id).clone(),
605                                 short_channel_id: channel.get_short_channel_id(),
606                                 remote_network_id: channel.get_their_node_id(),
607                                 channel_value_satoshis: channel.get_value_satoshis(),
608                                 user_id: channel.get_user_id(),
609                         });
610                 }
611                 res
612         }
613
614         /// Gets the list of usable channels, in random order. Useful as an argument to
615         /// Router::get_route to ensure non-announced channels are used.
616         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
617                 let channel_state = self.channel_state.lock().unwrap();
618                 let mut res = Vec::with_capacity(channel_state.by_id.len());
619                 for (channel_id, channel) in channel_state.by_id.iter() {
620                         // Note we use is_live here instead of usable which leads to somewhat confused
621                         // internal/external nomenclature, but that's ok cause that's probably what the user
622                         // really wanted anyway.
623                         if channel.is_live() {
624                                 res.push(ChannelDetails {
625                                         channel_id: (*channel_id).clone(),
626                                         short_channel_id: channel.get_short_channel_id(),
627                                         remote_network_id: channel.get_their_node_id(),
628                                         channel_value_satoshis: channel.get_value_satoshis(),
629                                         user_id: channel.get_user_id(),
630                                 });
631                         }
632                 }
633                 res
634         }
635
636         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
637         /// will be accepted on the given channel, and after additional timeout/the closing of all
638         /// pending HTLCs, the channel will be closed on chain.
639         ///
640         /// May generate a SendShutdown message event on success, which should be relayed.
641         pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
642                 let _ = self.total_consistency_lock.read().unwrap();
643
644                 let (mut failed_htlcs, chan_option) = {
645                         let mut channel_state_lock = self.channel_state.lock().unwrap();
646                         let channel_state = channel_state_lock.borrow_parts();
647                         match channel_state.by_id.entry(channel_id.clone()) {
648                                 hash_map::Entry::Occupied(mut chan_entry) => {
649                                         let (shutdown_msg, failed_htlcs) = chan_entry.get_mut().get_shutdown()?;
650                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
651                                                 node_id: chan_entry.get().get_their_node_id(),
652                                                 msg: shutdown_msg
653                                         });
654                                         if chan_entry.get().is_shutdown() {
655                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
656                                                         channel_state.short_to_id.remove(&short_id);
657                                                 }
658                                                 (failed_htlcs, Some(chan_entry.remove_entry().1))
659                                         } else { (failed_htlcs, None) }
660                                 },
661                                 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: "No such channel"})
662                         }
663                 };
664                 for htlc_source in failed_htlcs.drain(..) {
665                         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() });
666                 }
667                 let chan_update = if let Some(chan) = chan_option {
668                         if let Ok(update) = self.get_channel_update(&chan) {
669                                 Some(update)
670                         } else { None }
671                 } else { None };
672
673                 if let Some(update) = chan_update {
674                         let mut channel_state = self.channel_state.lock().unwrap();
675                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
676                                 msg: update
677                         });
678                 }
679
680                 Ok(())
681         }
682
683         #[inline]
684         fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
685                 let (local_txn, mut failed_htlcs) = shutdown_res;
686                 log_trace!(self, "Finishing force-closure of channel with {} transactions to broadcast and {} HTLCs to fail", local_txn.len(), failed_htlcs.len());
687                 for htlc_source in failed_htlcs.drain(..) {
688                         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() });
689                 }
690                 for tx in local_txn {
691                         self.tx_broadcaster.broadcast_transaction(&tx);
692                 }
693         }
694
695         /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
696         /// the chain and rejecting new HTLCs on the given channel.
697         pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
698                 let _ = self.total_consistency_lock.read().unwrap();
699
700                 let mut chan = {
701                         let mut channel_state_lock = self.channel_state.lock().unwrap();
702                         let channel_state = channel_state_lock.borrow_parts();
703                         if let Some(chan) = channel_state.by_id.remove(channel_id) {
704                                 if let Some(short_id) = chan.get_short_channel_id() {
705                                         channel_state.short_to_id.remove(&short_id);
706                                 }
707                                 chan
708                         } else {
709                                 return;
710                         }
711                 };
712                 log_trace!(self, "Force-closing channel {}", log_bytes!(channel_id[..]));
713                 self.finish_force_close_channel(chan.force_shutdown());
714                 if let Ok(update) = self.get_channel_update(&chan) {
715                         let mut channel_state = self.channel_state.lock().unwrap();
716                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
717                                 msg: update
718                         });
719                 }
720         }
721
722         /// Force close all channels, immediately broadcasting the latest local commitment transaction
723         /// for each to the chain and rejecting new HTLCs on each.
724         pub fn force_close_all_channels(&self) {
725                 for chan in self.list_channels() {
726                         self.force_close_channel(&chan.channel_id);
727                 }
728         }
729
730         #[inline]
731         fn gen_rho_mu_from_shared_secret(shared_secret: &[u8]) -> ([u8; 32], [u8; 32]) {
732                 assert_eq!(shared_secret.len(), 32);
733                 ({
734                         let mut hmac = Hmac::new(Sha256::new(), &[0x72, 0x68, 0x6f]); // rho
735                         hmac.input(&shared_secret[..]);
736                         let mut res = [0; 32];
737                         hmac.raw_result(&mut res);
738                         res
739                 },
740                 {
741                         let mut hmac = Hmac::new(Sha256::new(), &[0x6d, 0x75]); // mu
742                         hmac.input(&shared_secret[..]);
743                         let mut res = [0; 32];
744                         hmac.raw_result(&mut res);
745                         res
746                 })
747         }
748
749         #[inline]
750         fn gen_um_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
751                 assert_eq!(shared_secret.len(), 32);
752                 let mut hmac = Hmac::new(Sha256::new(), &[0x75, 0x6d]); // um
753                 hmac.input(&shared_secret[..]);
754                 let mut res = [0; 32];
755                 hmac.raw_result(&mut res);
756                 res
757         }
758
759         #[inline]
760         fn gen_ammag_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
761                 assert_eq!(shared_secret.len(), 32);
762                 let mut hmac = Hmac::new(Sha256::new(), &[0x61, 0x6d, 0x6d, 0x61, 0x67]); // ammag
763                 hmac.input(&shared_secret[..]);
764                 let mut res = [0; 32];
765                 hmac.raw_result(&mut res);
766                 res
767         }
768
769         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
770         #[inline]
771         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> {
772                 let mut blinded_priv = session_priv.clone();
773                 let mut blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
774
775                 for hop in route.hops.iter() {
776                         let shared_secret = SharedSecret::new(secp_ctx, &hop.pubkey, &blinded_priv);
777
778                         let mut sha = Sha256::new();
779                         sha.input(&blinded_pub.serialize()[..]);
780                         sha.input(&shared_secret[..]);
781                         let mut blinding_factor = [0u8; 32];
782                         sha.result(&mut blinding_factor);
783
784                         let ephemeral_pubkey = blinded_pub;
785
786                         blinded_priv.mul_assign(secp_ctx, &SecretKey::from_slice(secp_ctx, &blinding_factor)?)?;
787                         blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
788
789                         callback(shared_secret, blinding_factor, ephemeral_pubkey, hop);
790                 }
791
792                 Ok(())
793         }
794
795         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
796         fn construct_onion_keys<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey) -> Result<Vec<OnionKeys>, secp256k1::Error> {
797                 let mut res = Vec::with_capacity(route.hops.len());
798
799                 Self::construct_onion_keys_callback(secp_ctx, route, session_priv, |shared_secret, _blinding_factor, ephemeral_pubkey, _| {
800                         let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret[..]);
801
802                         res.push(OnionKeys {
803                                 #[cfg(test)]
804                                 shared_secret,
805                                 #[cfg(test)]
806                                 blinding_factor: _blinding_factor,
807                                 ephemeral_pubkey,
808                                 rho,
809                                 mu,
810                         });
811                 })?;
812
813                 Ok(res)
814         }
815
816         /// returns the hop data, as well as the first-hop value_msat and CLTV value we should send.
817         fn build_onion_payloads(route: &Route, starting_htlc_offset: u32) -> Result<(Vec<msgs::OnionHopData>, u64, u32), APIError> {
818                 let mut cur_value_msat = 0u64;
819                 let mut cur_cltv = starting_htlc_offset;
820                 let mut last_short_channel_id = 0;
821                 let mut res: Vec<msgs::OnionHopData> = Vec::with_capacity(route.hops.len());
822                 internal_traits::test_no_dealloc::<msgs::OnionHopData>(None);
823                 unsafe { res.set_len(route.hops.len()); }
824
825                 for (idx, hop) in route.hops.iter().enumerate().rev() {
826                         // First hop gets special values so that it can check, on receipt, that everything is
827                         // exactly as it should be (and the next hop isn't trying to probe to find out if we're
828                         // the intended recipient).
829                         let value_msat = if cur_value_msat == 0 { hop.fee_msat } else { cur_value_msat };
830                         let cltv = if cur_cltv == starting_htlc_offset { hop.cltv_expiry_delta + starting_htlc_offset } else { cur_cltv };
831                         res[idx] = msgs::OnionHopData {
832                                 realm: 0,
833                                 data: msgs::OnionRealm0HopData {
834                                         short_channel_id: last_short_channel_id,
835                                         amt_to_forward: value_msat,
836                                         outgoing_cltv_value: cltv,
837                                 },
838                                 hmac: [0; 32],
839                         };
840                         cur_value_msat += hop.fee_msat;
841                         if cur_value_msat >= 21000000 * 100000000 * 1000 {
842                                 return Err(APIError::RouteError{err: "Channel fees overflowed?!"});
843                         }
844                         cur_cltv += hop.cltv_expiry_delta as u32;
845                         if cur_cltv >= 500000000 {
846                                 return Err(APIError::RouteError{err: "Channel CLTV overflowed?!"});
847                         }
848                         last_short_channel_id = hop.short_channel_id;
849                 }
850                 Ok((res, cur_value_msat, cur_cltv))
851         }
852
853         #[inline]
854         fn shift_arr_right(arr: &mut [u8; 20*65]) {
855                 unsafe {
856                         ptr::copy(arr[0..].as_ptr(), arr[65..].as_mut_ptr(), 19*65);
857                 }
858                 for i in 0..65 {
859                         arr[i] = 0;
860                 }
861         }
862
863         #[inline]
864         fn xor_bufs(dst: &mut[u8], src: &[u8]) {
865                 assert_eq!(dst.len(), src.len());
866
867                 for i in 0..dst.len() {
868                         dst[i] ^= src[i];
869                 }
870         }
871
872         const ZERO:[u8; 21*65] = [0; 21*65];
873         fn construct_onion_packet(mut payloads: Vec<msgs::OnionHopData>, onion_keys: Vec<OnionKeys>, associated_data: &PaymentHash) -> msgs::OnionPacket {
874                 let mut buf = Vec::with_capacity(21*65);
875                 buf.resize(21*65, 0);
876
877                 let filler = {
878                         let iters = payloads.len() - 1;
879                         let end_len = iters * 65;
880                         let mut res = Vec::with_capacity(end_len);
881                         res.resize(end_len, 0);
882
883                         for (i, keys) in onion_keys.iter().enumerate() {
884                                 if i == payloads.len() - 1 { continue; }
885                                 let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
886                                 chacha.process(&ChannelManager::ZERO, &mut buf); // We don't have a seek function :(
887                                 ChannelManager::xor_bufs(&mut res[0..(i + 1)*65], &buf[(20 - i)*65..21*65]);
888                         }
889                         res
890                 };
891
892                 let mut packet_data = [0; 20*65];
893                 let mut hmac_res = [0; 32];
894
895                 for (i, (payload, keys)) in payloads.iter_mut().zip(onion_keys.iter()).rev().enumerate() {
896                         ChannelManager::shift_arr_right(&mut packet_data);
897                         payload.hmac = hmac_res;
898                         packet_data[0..65].copy_from_slice(&payload.encode()[..]);
899
900                         let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
901                         chacha.process(&packet_data, &mut buf[0..20*65]);
902                         packet_data[..].copy_from_slice(&buf[0..20*65]);
903
904                         if i == 0 {
905                                 packet_data[20*65 - filler.len()..20*65].copy_from_slice(&filler[..]);
906                         }
907
908                         let mut hmac = Hmac::new(Sha256::new(), &keys.mu);
909                         hmac.input(&packet_data);
910                         hmac.input(&associated_data.0[..]);
911                         hmac.raw_result(&mut hmac_res);
912                 }
913
914                 msgs::OnionPacket{
915                         version: 0,
916                         public_key: Ok(onion_keys.first().unwrap().ephemeral_pubkey),
917                         hop_data: packet_data,
918                         hmac: hmac_res,
919                 }
920         }
921
922         /// Encrypts a failure packet. raw_packet can either be a
923         /// msgs::DecodedOnionErrorPacket.encode() result or a msgs::OnionErrorPacket.data element.
924         fn encrypt_failure_packet(shared_secret: &[u8], raw_packet: &[u8]) -> msgs::OnionErrorPacket {
925                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
926
927                 let mut packet_crypted = Vec::with_capacity(raw_packet.len());
928                 packet_crypted.resize(raw_packet.len(), 0);
929                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
930                 chacha.process(&raw_packet, &mut packet_crypted[..]);
931                 msgs::OnionErrorPacket {
932                         data: packet_crypted,
933                 }
934         }
935
936         fn build_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::DecodedOnionErrorPacket {
937                 assert_eq!(shared_secret.len(), 32);
938                 assert!(failure_data.len() <= 256 - 2);
939
940                 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
941
942                 let failuremsg = {
943                         let mut res = Vec::with_capacity(2 + failure_data.len());
944                         res.push(((failure_type >> 8) & 0xff) as u8);
945                         res.push(((failure_type >> 0) & 0xff) as u8);
946                         res.extend_from_slice(&failure_data[..]);
947                         res
948                 };
949                 let pad = {
950                         let mut res = Vec::with_capacity(256 - 2 - failure_data.len());
951                         res.resize(256 - 2 - failure_data.len(), 0);
952                         res
953                 };
954                 let mut packet = msgs::DecodedOnionErrorPacket {
955                         hmac: [0; 32],
956                         failuremsg: failuremsg,
957                         pad: pad,
958                 };
959
960                 let mut hmac = Hmac::new(Sha256::new(), &um);
961                 hmac.input(&packet.encode()[32..]);
962                 hmac.raw_result(&mut packet.hmac);
963
964                 packet
965         }
966
967         #[inline]
968         fn build_first_hop_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::OnionErrorPacket {
969                 let failure_packet = ChannelManager::build_failure_packet(shared_secret, failure_type, failure_data);
970                 ChannelManager::encrypt_failure_packet(shared_secret, &failure_packet.encode()[..])
971         }
972
973         fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder>) {
974                 macro_rules! get_onion_hash {
975                         () => {
976                                 {
977                                         let mut sha = Sha256::new();
978                                         sha.input(&msg.onion_routing_packet.hop_data);
979                                         let mut onion_hash = [0; 32];
980                                         sha.result(&mut onion_hash);
981                                         onion_hash
982                                 }
983                         }
984                 }
985
986                 if let Err(_) = msg.onion_routing_packet.public_key {
987                         log_info!(self, "Failed to accept/forward incoming HTLC with invalid ephemeral pubkey");
988                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
989                                 channel_id: msg.channel_id,
990                                 htlc_id: msg.htlc_id,
991                                 sha256_of_onion: get_onion_hash!(),
992                                 failure_code: 0x8000 | 0x4000 | 6,
993                         })), self.channel_state.lock().unwrap());
994                 }
995
996                 let shared_secret = {
997                         let mut arr = [0; 32];
998                         arr.copy_from_slice(&SharedSecret::new(&self.secp_ctx, &msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key)[..]);
999                         arr
1000                 };
1001                 let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
1002
1003                 let mut channel_state = None;
1004                 macro_rules! return_err {
1005                         ($msg: expr, $err_code: expr, $data: expr) => {
1006                                 {
1007                                         log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
1008                                         if channel_state.is_none() {
1009                                                 channel_state = Some(self.channel_state.lock().unwrap());
1010                                         }
1011                                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
1012                                                 channel_id: msg.channel_id,
1013                                                 htlc_id: msg.htlc_id,
1014                                                 reason: ChannelManager::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
1015                                         })), channel_state.unwrap());
1016                                 }
1017                         }
1018                 }
1019
1020                 if msg.onion_routing_packet.version != 0 {
1021                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
1022                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
1023                         //the hash doesn't really serve any purpuse - in the case of hashing all data, the
1024                         //receiving node would have to brute force to figure out which version was put in the
1025                         //packet by the node that send us the message, in the case of hashing the hop_data, the
1026                         //node knows the HMAC matched, so they already know what is there...
1027                         return_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4, &get_onion_hash!());
1028                 }
1029
1030                 let mut hmac = Hmac::new(Sha256::new(), &mu);
1031                 hmac.input(&msg.onion_routing_packet.hop_data);
1032                 hmac.input(&msg.payment_hash.0[..]);
1033                 if hmac.result() != MacResult::new(&msg.onion_routing_packet.hmac) {
1034                         return_err!("HMAC Check failed", 0x8000 | 0x4000 | 5, &get_onion_hash!());
1035                 }
1036
1037                 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
1038                 let next_hop_data = {
1039                         let mut decoded = [0; 65];
1040                         chacha.process(&msg.onion_routing_packet.hop_data[0..65], &mut decoded);
1041                         match msgs::OnionHopData::read(&mut Cursor::new(&decoded[..])) {
1042                                 Err(err) => {
1043                                         let error_code = match err {
1044                                                 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
1045                                                 _ => 0x2000 | 2, // Should never happen
1046                                         };
1047                                         return_err!("Unable to decode our hop data", error_code, &[0;0]);
1048                                 },
1049                                 Ok(msg) => msg
1050                         }
1051                 };
1052
1053                 let pending_forward_info = if next_hop_data.hmac == [0; 32] {
1054                                 // OUR PAYMENT!
1055                                 // final_expiry_too_soon
1056                                 if (msg.cltv_expiry as u64) < self.latest_block_height.load(Ordering::Acquire) as u64 + (CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS) as u64 {
1057                                         return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
1058                                 }
1059                                 // final_incorrect_htlc_amount
1060                                 if next_hop_data.data.amt_to_forward > msg.amount_msat {
1061                                         return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
1062                                 }
1063                                 // final_incorrect_cltv_expiry
1064                                 if next_hop_data.data.outgoing_cltv_value != msg.cltv_expiry {
1065                                         return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
1066                                 }
1067
1068                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
1069                                 // message, however that would leak that we are the recipient of this payment, so
1070                                 // instead we stay symmetric with the forwarding case, only responding (after a
1071                                 // delay) once they've send us a commitment_signed!
1072
1073                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1074                                         onion_packet: None,
1075                                         payment_hash: msg.payment_hash.clone(),
1076                                         short_channel_id: 0,
1077                                         incoming_shared_secret: shared_secret,
1078                                         amt_to_forward: next_hop_data.data.amt_to_forward,
1079                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1080                                 })
1081                         } else {
1082                                 let mut new_packet_data = [0; 20*65];
1083                                 chacha.process(&msg.onion_routing_packet.hop_data[65..], &mut new_packet_data[0..19*65]);
1084                                 chacha.process(&ChannelManager::ZERO[0..65], &mut new_packet_data[19*65..]);
1085
1086                                 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
1087
1088                                 let blinding_factor = {
1089                                         let mut sha = Sha256::new();
1090                                         sha.input(&new_pubkey.serialize()[..]);
1091                                         sha.input(&shared_secret);
1092                                         let mut res = [0u8; 32];
1093                                         sha.result(&mut res);
1094                                         match SecretKey::from_slice(&self.secp_ctx, &res) {
1095                                                 Err(_) => {
1096                                                         return_err!("Blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
1097                                                 },
1098                                                 Ok(key) => key
1099                                         }
1100                                 };
1101
1102                                 if let Err(_) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor) {
1103                                         return_err!("New blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
1104                                 }
1105
1106                                 let outgoing_packet = msgs::OnionPacket {
1107                                         version: 0,
1108                                         public_key: Ok(new_pubkey),
1109                                         hop_data: new_packet_data,
1110                                         hmac: next_hop_data.hmac.clone(),
1111                                 };
1112
1113                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1114                                         onion_packet: Some(outgoing_packet),
1115                                         payment_hash: msg.payment_hash.clone(),
1116                                         short_channel_id: next_hop_data.data.short_channel_id,
1117                                         incoming_shared_secret: shared_secret,
1118                                         amt_to_forward: next_hop_data.data.amt_to_forward,
1119                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1120                                 })
1121                         };
1122
1123                 channel_state = Some(self.channel_state.lock().unwrap());
1124                 if let &PendingHTLCStatus::Forward(PendingForwardHTLCInfo { ref onion_packet, ref short_channel_id, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
1125                         if onion_packet.is_some() { // If short_channel_id is 0 here, we'll reject them in the body here
1126                                 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
1127                                 let forwarding_id = match id_option {
1128                                         None => { // unknown_next_peer
1129                                                 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
1130                                         },
1131                                         Some(id) => id.clone(),
1132                                 };
1133                                 if let Some((err, code, chan_update)) = loop {
1134                                         let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
1135
1136                                         // Note that we could technically not return an error yet here and just hope
1137                                         // that the connection is reestablished or monitor updated by the time we get
1138                                         // around to doing the actual forward, but better to fail early if we can and
1139                                         // hopefully an attacker trying to path-trace payments cannot make this occur
1140                                         // on a small/per-node/per-channel scale.
1141                                         if !chan.is_live() { // channel_disabled
1142                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
1143                                         }
1144                                         if *amt_to_forward < chan.get_their_htlc_minimum_msat() { // amount_below_minimum
1145                                                 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
1146                                         }
1147                                         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) });
1148                                         if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
1149                                                 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())));
1150                                         }
1151                                         if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 { // incorrect_cltv_expiry
1152                                                 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())));
1153                                         }
1154                                         let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1155                                         // We want to have at least HTLC_FAIL_TIMEOUT_BLOCKS to fail prior to going on chain CLAIM_BUFFER blocks before expiration
1156                                         if msg.cltv_expiry <= cur_height + CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS as u32 { // expiry_too_soon
1157                                                 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1158                                         }
1159                                         if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
1160                                                 break Some(("CLTV expiry is too far in the future", 21, None));
1161                                         }
1162                                         break None;
1163                                 }
1164                                 {
1165                                         let mut res = Vec::with_capacity(8 + 128);
1166                                         if code == 0x1000 | 11 || code == 0x1000 | 12 {
1167                                                 res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
1168                                         }
1169                                         else if code == 0x1000 | 13 {
1170                                                 res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
1171                                         }
1172                                         if let Some(chan_update) = chan_update {
1173                                                 res.extend_from_slice(&chan_update.encode_with_len()[..]);
1174                                         }
1175                                         return_err!(err, code, &res[..]);
1176                                 }
1177                         }
1178                 }
1179
1180                 (pending_forward_info, channel_state.unwrap())
1181         }
1182
1183         /// only fails if the channel does not yet have an assigned short_id
1184         /// May be called with channel_state already locked!
1185         fn get_channel_update(&self, chan: &Channel) -> Result<msgs::ChannelUpdate, HandleError> {
1186                 let short_channel_id = match chan.get_short_channel_id() {
1187                         None => return Err(HandleError{err: "Channel not yet established", action: None}),
1188                         Some(id) => id,
1189                 };
1190
1191                 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_their_node_id().serialize()[..];
1192
1193                 let unsigned = msgs::UnsignedChannelUpdate {
1194                         chain_hash: self.genesis_hash,
1195                         short_channel_id: short_channel_id,
1196                         timestamp: chan.get_channel_update_count(),
1197                         flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
1198                         cltv_expiry_delta: CLTV_EXPIRY_DELTA,
1199                         htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
1200                         fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
1201                         fee_proportional_millionths: chan.get_fee_proportional_millionths(),
1202                         excess_data: Vec::new(),
1203                 };
1204
1205                 let msg_hash = Sha256dHash::from_data(&unsigned.encode()[..]);
1206                 let sig = self.secp_ctx.sign(&Message::from_slice(&msg_hash[..]).unwrap(), &self.our_network_key);
1207
1208                 Ok(msgs::ChannelUpdate {
1209                         signature: sig,
1210                         contents: unsigned
1211                 })
1212         }
1213
1214         /// Sends a payment along a given route.
1215         ///
1216         /// Value parameters are provided via the last hop in route, see documentation for RouteHop
1217         /// fields for more info.
1218         ///
1219         /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
1220         /// payment), we don't do anything to stop you! We always try to ensure that if the provided
1221         /// next hop knows the preimage to payment_hash they can claim an additional amount as
1222         /// specified in the last hop in the route! Thus, you should probably do your own
1223         /// payment_preimage tracking (which you should already be doing as they represent "proof of
1224         /// payment") and prevent double-sends yourself.
1225         ///
1226         /// May generate a SendHTLCs message event on success, which should be relayed.
1227         ///
1228         /// Raises APIError::RoutError when invalid route or forward parameter
1229         /// (cltv_delta, fee, node public key) is specified.
1230         /// Raises APIError::ChannelUnavailable if the next-hop channel is not available for updates
1231         /// (including due to previous monitor update failure or new permanent monitor update failure).
1232         /// Raised APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
1233         /// relevant updates.
1234         ///
1235         /// In case of APIError::RouteError/APIError::ChannelUnavailable, the payment send has failed
1236         /// and you may wish to retry via a different route immediately.
1237         /// In case of APIError::MonitorUpdateFailed, the commitment update has been irrevocably
1238         /// committed on our end and we're just waiting for a monitor update to send it. Do NOT retry
1239         /// the payment via a different route unless you intend to pay twice!
1240         pub fn send_payment(&self, route: Route, payment_hash: PaymentHash) -> Result<(), APIError> {
1241                 if route.hops.len() < 1 || route.hops.len() > 20 {
1242                         return Err(APIError::RouteError{err: "Route didn't go anywhere/had bogus size"});
1243                 }
1244                 let our_node_id = self.get_our_node_id();
1245                 for (idx, hop) in route.hops.iter().enumerate() {
1246                         if idx != route.hops.len() - 1 && hop.pubkey == our_node_id {
1247                                 return Err(APIError::RouteError{err: "Route went through us but wasn't a simple rebalance loop to us"});
1248                         }
1249                 }
1250
1251                 let session_priv = self.keys_manager.get_session_key();
1252
1253                 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1254
1255                 let onion_keys = secp_call!(ChannelManager::construct_onion_keys(&self.secp_ctx, &route, &session_priv),
1256                                 APIError::RouteError{err: "Pubkey along hop was maliciously selected"});
1257                 let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height)?;
1258                 let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
1259
1260                 let _ = self.total_consistency_lock.read().unwrap();
1261
1262                 let err: Result<(), _> = loop {
1263                         let mut channel_lock = self.channel_state.lock().unwrap();
1264
1265                         let id = match channel_lock.short_to_id.get(&route.hops.first().unwrap().short_channel_id) {
1266                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!"}),
1267                                 Some(id) => id.clone(),
1268                         };
1269
1270                         let channel_state = channel_lock.borrow_parts();
1271                         if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) {
1272                                 match {
1273                                         if chan.get().get_their_node_id() != route.hops.first().unwrap().pubkey {
1274                                                 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1275                                         }
1276                                         if !chan.get().is_live() {
1277                                                 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!"});
1278                                         }
1279                                         break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1280                                                 route: route.clone(),
1281                                                 session_priv: session_priv.clone(),
1282                                                 first_hop_htlc_msat: htlc_msat,
1283                                         }, onion_packet), channel_state, chan)
1284                                 } {
1285                                         Some((update_add, commitment_signed, chan_monitor)) => {
1286                                                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1287                                                         maybe_break_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst);
1288                                                         // Note that MonitorUpdateFailed here indicates (per function docs)
1289                                                         // that we will resent the commitment update once we unfree monitor
1290                                                         // updating, so we have to take special care that we don't return
1291                                                         // something else in case we will resend later!
1292                                                         return Err(APIError::MonitorUpdateFailed);
1293                                                 }
1294
1295                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1296                                                         node_id: route.hops.first().unwrap().pubkey,
1297                                                         updates: msgs::CommitmentUpdate {
1298                                                                 update_add_htlcs: vec![update_add],
1299                                                                 update_fulfill_htlcs: Vec::new(),
1300                                                                 update_fail_htlcs: Vec::new(),
1301                                                                 update_fail_malformed_htlcs: Vec::new(),
1302                                                                 update_fee: None,
1303                                                                 commitment_signed,
1304                                                         },
1305                                                 });
1306                                         },
1307                                         None => {},
1308                                 }
1309                         } else { unreachable!(); }
1310                         return Ok(());
1311                 };
1312
1313                 match handle_error!(self, err, route.hops.first().unwrap().pubkey) {
1314                         Ok(_) => unreachable!(),
1315                         Err(e) => {
1316                                 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
1317                                 } else {
1318                                         log_error!(self, "Got bad keys: {}!", e.err);
1319                                         let mut channel_state = self.channel_state.lock().unwrap();
1320                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1321                                                 node_id: route.hops.first().unwrap().pubkey,
1322                                                 action: e.action,
1323                                         });
1324                                 }
1325                                 Err(APIError::ChannelUnavailable { err: e.err })
1326                         },
1327                 }
1328         }
1329
1330         /// Call this upon creation of a funding transaction for the given channel.
1331         ///
1332         /// Note that ALL inputs in the transaction pointed to by funding_txo MUST spend SegWit outputs
1333         /// or your counterparty can steal your funds!
1334         ///
1335         /// Panics if a funding transaction has already been provided for this channel.
1336         ///
1337         /// May panic if the funding_txo is duplicative with some other channel (note that this should
1338         /// be trivially prevented by using unique funding transaction keys per-channel).
1339         pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1340                 let _ = self.total_consistency_lock.read().unwrap();
1341
1342                 let (chan, msg, chan_monitor) = {
1343                         let (res, chan) = {
1344                                 let mut channel_state = self.channel_state.lock().unwrap();
1345                                 match channel_state.by_id.remove(temporary_channel_id) {
1346                                         Some(mut chan) => {
1347                                                 (chan.get_outbound_funding_created(funding_txo)
1348                                                         .map_err(|e| if let ChannelError::Close(msg) = e {
1349                                                                 MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.force_shutdown(), None)
1350                                                         } else { unreachable!(); })
1351                                                 , chan)
1352                                         },
1353                                         None => return
1354                                 }
1355                         };
1356                         match handle_error!(self, res, chan.get_their_node_id()) {
1357                                 Ok(funding_msg) => {
1358                                         (chan, funding_msg.0, funding_msg.1)
1359                                 },
1360                                 Err(e) => {
1361                                         log_error!(self, "Got bad signatures: {}!", e.err);
1362                                         let mut channel_state = self.channel_state.lock().unwrap();
1363                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1364                                                 node_id: chan.get_their_node_id(),
1365                                                 action: e.action,
1366                                         });
1367                                         return;
1368                                 },
1369                         }
1370                 };
1371                 // Because we have exclusive ownership of the channel here we can release the channel_state
1372                 // lock before add_update_monitor
1373                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1374                         unimplemented!();
1375                 }
1376
1377                 let mut channel_state = self.channel_state.lock().unwrap();
1378                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
1379                         node_id: chan.get_their_node_id(),
1380                         msg: msg,
1381                 });
1382                 match channel_state.by_id.entry(chan.channel_id()) {
1383                         hash_map::Entry::Occupied(_) => {
1384                                 panic!("Generated duplicate funding txid?");
1385                         },
1386                         hash_map::Entry::Vacant(e) => {
1387                                 e.insert(chan);
1388                         }
1389                 }
1390         }
1391
1392         fn get_announcement_sigs(&self, chan: &Channel) -> Option<msgs::AnnouncementSignatures> {
1393                 if !chan.should_announce() { return None }
1394
1395                 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1396                         Ok(res) => res,
1397                         Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1398                 };
1399                 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
1400                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1401
1402                 Some(msgs::AnnouncementSignatures {
1403                         channel_id: chan.channel_id(),
1404                         short_channel_id: chan.get_short_channel_id().unwrap(),
1405                         node_signature: our_node_sig,
1406                         bitcoin_signature: our_bitcoin_sig,
1407                 })
1408         }
1409
1410         /// Processes HTLCs which are pending waiting on random forward delay.
1411         ///
1412         /// Should only really ever be called in response to an PendingHTLCsForwardable event.
1413         /// Will likely generate further events.
1414         pub fn process_pending_htlc_forwards(&self) {
1415                 let _ = self.total_consistency_lock.read().unwrap();
1416
1417                 let mut new_events = Vec::new();
1418                 let mut failed_forwards = Vec::new();
1419                 {
1420                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1421                         let channel_state = channel_state_lock.borrow_parts();
1422
1423                         if cfg!(not(feature = "fuzztarget")) && Instant::now() < *channel_state.next_forward {
1424                                 return;
1425                         }
1426
1427                         for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1428                                 if short_chan_id != 0 {
1429                                         let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1430                                                 Some(chan_id) => chan_id.clone(),
1431                                                 None => {
1432                                                         failed_forwards.reserve(pending_forwards.len());
1433                                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1434                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1435                                                                         short_channel_id: prev_short_channel_id,
1436                                                                         htlc_id: prev_htlc_id,
1437                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1438                                                                 });
1439                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
1440                                                         }
1441                                                         continue;
1442                                                 }
1443                                         };
1444                                         let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();
1445
1446                                         let mut add_htlc_msgs = Vec::new();
1447                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1448                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1449                                                         short_channel_id: prev_short_channel_id,
1450                                                         htlc_id: prev_htlc_id,
1451                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1452                                                 });
1453                                                 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()) {
1454                                                         Err(_e) => {
1455                                                                 let chan_update = self.get_channel_update(forward_chan).unwrap();
1456                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x1000 | 7, Some(chan_update)));
1457                                                                 continue;
1458                                                         },
1459                                                         Ok(update_add) => {
1460                                                                 match update_add {
1461                                                                         Some(msg) => { add_htlc_msgs.push(msg); },
1462                                                                         None => {
1463                                                                                 // Nothing to do here...we're waiting on a remote
1464                                                                                 // revoke_and_ack before we can add anymore HTLCs. The Channel
1465                                                                                 // will automatically handle building the update_add_htlc and
1466                                                                                 // commitment_signed messages when we can.
1467                                                                                 // TODO: Do some kind of timer to set the channel as !is_live()
1468                                                                                 // as we don't really want others relying on us relaying through
1469                                                                                 // this channel currently :/.
1470                                                                         }
1471                                                                 }
1472                                                         }
1473                                                 }
1474                                         }
1475
1476                                         if !add_htlc_msgs.is_empty() {
1477                                                 let (commitment_msg, monitor) = match forward_chan.send_commitment() {
1478                                                         Ok(res) => res,
1479                                                         Err(e) => {
1480                                                                 if let ChannelError::Ignore(_) = e {
1481                                                                         panic!("Stated return value requirements in send_commitment() were not met");
1482                                                                 }
1483                                                                 //TODO: Handle...this is bad!
1484                                                                 continue;
1485                                                         },
1486                                                 };
1487                                                 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
1488                                                         unimplemented!();
1489                                                 }
1490                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1491                                                         node_id: forward_chan.get_their_node_id(),
1492                                                         updates: msgs::CommitmentUpdate {
1493                                                                 update_add_htlcs: add_htlc_msgs,
1494                                                                 update_fulfill_htlcs: Vec::new(),
1495                                                                 update_fail_htlcs: Vec::new(),
1496                                                                 update_fail_malformed_htlcs: Vec::new(),
1497                                                                 update_fee: None,
1498                                                                 commitment_signed: commitment_msg,
1499                                                         },
1500                                                 });
1501                                         }
1502                                 } else {
1503                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1504                                                 let prev_hop_data = HTLCPreviousHopData {
1505                                                         short_channel_id: prev_short_channel_id,
1506                                                         htlc_id: prev_htlc_id,
1507                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1508                                                 };
1509                                                 match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
1510                                                         hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(prev_hop_data),
1511                                                         hash_map::Entry::Vacant(entry) => { entry.insert(vec![prev_hop_data]); },
1512                                                 };
1513                                                 new_events.push(events::Event::PaymentReceived {
1514                                                         payment_hash: forward_info.payment_hash,
1515                                                         amt: forward_info.amt_to_forward,
1516                                                 });
1517                                         }
1518                                 }
1519                         }
1520                 }
1521
1522                 for (htlc_source, payment_hash, failure_code, update) in failed_forwards.drain(..) {
1523                         match update {
1524                                 None => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code, data: Vec::new() }),
1525                                 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() }),
1526                         };
1527                 }
1528
1529                 if new_events.is_empty() { return }
1530                 let mut events = self.pending_events.lock().unwrap();
1531                 events.append(&mut new_events);
1532         }
1533
1534         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect after a PaymentReceived event.
1535         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash, reason: PaymentFailReason) -> bool {
1536                 let _ = self.total_consistency_lock.read().unwrap();
1537
1538                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1539                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(payment_hash);
1540                 if let Some(mut sources) = removed_source {
1541                         for htlc_with_hash in sources.drain(..) {
1542                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1543                                 self.fail_htlc_backwards_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_hash, HTLCFailReason::Reason { failure_code: if reason == PaymentFailReason::PreimageUnknown {0x4000 | 15} else {0x4000 | 16}, data: Vec::new() });
1544                         }
1545                         true
1546                 } else { false }
1547         }
1548
1549         /// Fails an HTLC backwards to the sender of it to us.
1550         /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
1551         /// There are several callsites that do stupid things like loop over a list of payment_hashes
1552         /// to fail and take the channel_state lock for each iteration (as we take ownership and may
1553         /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
1554         /// still-available channels.
1555         fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
1556                 match source {
1557                         HTLCSource::OutboundRoute { ref route, .. } => {
1558                                 log_trace!(self, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1559                                 mem::drop(channel_state_lock);
1560                                 match &onion_error {
1561                                         &HTLCFailReason::ErrorPacket { ref err } => {
1562                                                 let (channel_update, payment_retryable) = self.process_onion_failure(&source, err.data.clone());
1563                                                 if let Some(update) = channel_update {
1564                                                         self.channel_state.lock().unwrap().pending_msg_events.push(
1565                                                                 events::MessageSendEvent::PaymentFailureNetworkUpdate {
1566                                                                         update,
1567                                                                 }
1568                                                         );
1569                                                 }
1570                                                 self.pending_events.lock().unwrap().push(
1571                                                         events::Event::PaymentFailed {
1572                                                                 payment_hash: payment_hash.clone(),
1573                                                                 rejected_by_dest: !payment_retryable,
1574                                                         }
1575                                                 );
1576                                         },
1577                                         &HTLCFailReason::Reason { .. } => {
1578                                                 // we get a fail_malformed_htlc from the first hop
1579                                                 // TODO: We'd like to generate a PaymentFailureNetworkUpdate for temporary
1580                                                 // failures here, but that would be insufficient as Router::get_route
1581                                                 // generally ignores its view of our own channels as we provide them via
1582                                                 // ChannelDetails.
1583                                                 // TODO: For non-temporary failures, we really should be closing the
1584                                                 // channel here as we apparently can't relay through them anyway.
1585                                                 self.pending_events.lock().unwrap().push(
1586                                                         events::Event::PaymentFailed {
1587                                                                 payment_hash: payment_hash.clone(),
1588                                                                 rejected_by_dest: route.hops.len() == 1,
1589                                                         }
1590                                                 );
1591                                         }
1592                                 }
1593                         },
1594                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
1595                                 let err_packet = match onion_error {
1596                                         HTLCFailReason::Reason { failure_code, data } => {
1597                                                 log_trace!(self, "Failing HTLC with payment_hash {} backwards from us with code {}", log_bytes!(payment_hash.0), failure_code);
1598                                                 let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1599                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1600                                         },
1601                                         HTLCFailReason::ErrorPacket { err } => {
1602                                                 log_trace!(self, "Failing HTLC with payment_hash {} backwards with pre-built ErrorPacket", log_bytes!(payment_hash.0));
1603                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1604                                         }
1605                                 };
1606
1607                                 let channel_state = channel_state_lock.borrow_parts();
1608
1609                                 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1610                                         Some(chan_id) => chan_id.clone(),
1611                                         None => return
1612                                 };
1613
1614                                 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1615                                 match chan.get_update_fail_htlc_and_commit(htlc_id, err_packet) {
1616                                         Ok(Some((msg, commitment_msg, chan_monitor))) => {
1617                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1618                                                         unimplemented!();
1619                                                 }
1620                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1621                                                         node_id: chan.get_their_node_id(),
1622                                                         updates: msgs::CommitmentUpdate {
1623                                                                 update_add_htlcs: Vec::new(),
1624                                                                 update_fulfill_htlcs: Vec::new(),
1625                                                                 update_fail_htlcs: vec![msg],
1626                                                                 update_fail_malformed_htlcs: Vec::new(),
1627                                                                 update_fee: None,
1628                                                                 commitment_signed: commitment_msg,
1629                                                         },
1630                                                 });
1631                                         },
1632                                         Ok(None) => {},
1633                                         Err(_e) => {
1634                                                 //TODO: Do something with e?
1635                                                 return;
1636                                         },
1637                                 }
1638                         },
1639                 }
1640         }
1641
1642         /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1643         /// generating message events for the net layer to claim the payment, if possible. Thus, you
1644         /// should probably kick the net layer to go send messages if this returns true!
1645         ///
1646         /// May panic if called except in response to a PaymentReceived event.
1647         pub fn claim_funds(&self, payment_preimage: PaymentPreimage) -> bool {
1648                 let mut sha = Sha256::new();
1649                 sha.input(&payment_preimage.0[..]);
1650                 let mut payment_hash = PaymentHash([0; 32]);
1651                 sha.result(&mut payment_hash.0[..]);
1652
1653                 let _ = self.total_consistency_lock.read().unwrap();
1654
1655                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1656                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&payment_hash);
1657                 if let Some(mut sources) = removed_source {
1658                         for htlc_with_hash in sources.drain(..) {
1659                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1660                                 self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_preimage);
1661                         }
1662                         true
1663                 } else { false }
1664         }
1665         fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_preimage: PaymentPreimage) {
1666                 match source {
1667                         HTLCSource::OutboundRoute { .. } => {
1668                                 mem::drop(channel_state_lock);
1669                                 let mut pending_events = self.pending_events.lock().unwrap();
1670                                 pending_events.push(events::Event::PaymentSent {
1671                                         payment_preimage
1672                                 });
1673                         },
1674                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, .. }) => {
1675                                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1676                                 let channel_state = channel_state_lock.borrow_parts();
1677
1678                                 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1679                                         Some(chan_id) => chan_id.clone(),
1680                                         None => {
1681                                                 // TODO: There is probably a channel manager somewhere that needs to
1682                                                 // learn the preimage as the channel already hit the chain and that's
1683                                                 // why its missing.
1684                                                 return
1685                                         }
1686                                 };
1687
1688                                 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1689                                 match chan.get_update_fulfill_htlc_and_commit(htlc_id, payment_preimage) {
1690                                         Ok((msgs, monitor_option)) => {
1691                                                 if let Some(chan_monitor) = monitor_option {
1692                                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1693                                                                 unimplemented!();// but def dont push the event...
1694                                                         }
1695                                                 }
1696                                                 if let Some((msg, commitment_signed)) = msgs {
1697                                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1698                                                                 node_id: chan.get_their_node_id(),
1699                                                                 updates: msgs::CommitmentUpdate {
1700                                                                         update_add_htlcs: Vec::new(),
1701                                                                         update_fulfill_htlcs: vec![msg],
1702                                                                         update_fail_htlcs: Vec::new(),
1703                                                                         update_fail_malformed_htlcs: Vec::new(),
1704                                                                         update_fee: None,
1705                                                                         commitment_signed,
1706                                                                 }
1707                                                         });
1708                                                 }
1709                                         },
1710                                         Err(_e) => {
1711                                                 // TODO: There is probably a channel manager somewhere that needs to
1712                                                 // learn the preimage as the channel may be about to hit the chain.
1713                                                 //TODO: Do something with e?
1714                                                 return
1715                                         },
1716                                 }
1717                         },
1718                 }
1719         }
1720
1721         /// Gets the node_id held by this ChannelManager
1722         pub fn get_our_node_id(&self) -> PublicKey {
1723                 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
1724         }
1725
1726         /// Used to restore channels to normal operation after a
1727         /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
1728         /// operation.
1729         pub fn test_restore_channel_monitor(&self) {
1730                 let mut close_results = Vec::new();
1731                 let mut htlc_forwards = Vec::new();
1732                 let mut htlc_failures = Vec::new();
1733                 let _ = self.total_consistency_lock.read().unwrap();
1734
1735                 {
1736                         let mut channel_lock = self.channel_state.lock().unwrap();
1737                         let channel_state = channel_lock.borrow_parts();
1738                         let short_to_id = channel_state.short_to_id;
1739                         let pending_msg_events = channel_state.pending_msg_events;
1740                         channel_state.by_id.retain(|_, channel| {
1741                                 if channel.is_awaiting_monitor_update() {
1742                                         let chan_monitor = channel.channel_monitor();
1743                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1744                                                 match e {
1745                                                         ChannelMonitorUpdateErr::PermanentFailure => {
1746                                                                 // TODO: There may be some pending HTLCs that we intended to fail
1747                                                                 // backwards when a monitor update failed. We should make sure
1748                                                                 // knowledge of those gets moved into the appropriate in-memory
1749                                                                 // ChannelMonitor and they get failed backwards once we get
1750                                                                 // on-chain confirmations.
1751                                                                 // Note I think #198 addresses this, so once its merged a test
1752                                                                 // should be written.
1753                                                                 if let Some(short_id) = channel.get_short_channel_id() {
1754                                                                         short_to_id.remove(&short_id);
1755                                                                 }
1756                                                                 close_results.push(channel.force_shutdown());
1757                                                                 if let Ok(update) = self.get_channel_update(&channel) {
1758                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1759                                                                                 msg: update
1760                                                                         });
1761                                                                 }
1762                                                                 false
1763                                                         },
1764                                                         ChannelMonitorUpdateErr::TemporaryFailure => true,
1765                                                 }
1766                                         } else {
1767                                                 let (raa, commitment_update, order, pending_forwards, mut pending_failures) = channel.monitor_updating_restored();
1768                                                 if !pending_forwards.is_empty() {
1769                                                         htlc_forwards.push((channel.get_short_channel_id().expect("We can't have pending forwards before funding confirmation"), pending_forwards));
1770                                                 }
1771                                                 htlc_failures.append(&mut pending_failures);
1772
1773                                                 macro_rules! handle_cs { () => {
1774                                                         if let Some(update) = commitment_update {
1775                                                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1776                                                                         node_id: channel.get_their_node_id(),
1777                                                                         updates: update,
1778                                                                 });
1779                                                         }
1780                                                 } }
1781                                                 macro_rules! handle_raa { () => {
1782                                                         if let Some(revoke_and_ack) = raa {
1783                                                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
1784                                                                         node_id: channel.get_their_node_id(),
1785                                                                         msg: revoke_and_ack,
1786                                                                 });
1787                                                         }
1788                                                 } }
1789                                                 match order {
1790                                                         RAACommitmentOrder::CommitmentFirst => {
1791                                                                 handle_cs!();
1792                                                                 handle_raa!();
1793                                                         },
1794                                                         RAACommitmentOrder::RevokeAndACKFirst => {
1795                                                                 handle_raa!();
1796                                                                 handle_cs!();
1797                                                         },
1798                                                 }
1799                                                 true
1800                                         }
1801                                 } else { true }
1802                         });
1803                 }
1804
1805                 for failure in htlc_failures.drain(..) {
1806                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
1807                 }
1808                 self.forward_htlcs(&mut htlc_forwards[..]);
1809
1810                 for res in close_results.drain(..) {
1811                         self.finish_force_close_channel(res);
1812                 }
1813         }
1814
1815         fn internal_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
1816                 if msg.chain_hash != self.genesis_hash {
1817                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash", msg.temporary_channel_id.clone()));
1818                 }
1819
1820                 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)
1821                         .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
1822                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1823                 let channel_state = channel_state_lock.borrow_parts();
1824                 match channel_state.by_id.entry(channel.channel_id()) {
1825                         hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!", msg.temporary_channel_id.clone())),
1826                         hash_map::Entry::Vacant(entry) => {
1827                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
1828                                         node_id: their_node_id.clone(),
1829                                         msg: channel.get_accept_channel(),
1830                                 });
1831                                 entry.insert(channel);
1832                         }
1833                 }
1834                 Ok(())
1835         }
1836
1837         fn internal_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
1838                 let (value, output_script, user_id) = {
1839                         let mut channel_lock = self.channel_state.lock().unwrap();
1840                         let channel_state = channel_lock.borrow_parts();
1841                         match channel_state.by_id.entry(msg.temporary_channel_id) {
1842                                 hash_map::Entry::Occupied(mut chan) => {
1843                                         if chan.get().get_their_node_id() != *their_node_id {
1844                                                 //TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
1845                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1846                                         }
1847                                         try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration), channel_state, chan);
1848                                         (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
1849                                 },
1850                                 //TODO: same as above
1851                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1852                         }
1853                 };
1854                 let mut pending_events = self.pending_events.lock().unwrap();
1855                 pending_events.push(events::Event::FundingGenerationReady {
1856                         temporary_channel_id: msg.temporary_channel_id,
1857                         channel_value_satoshis: value,
1858                         output_script: output_script,
1859                         user_channel_id: user_id,
1860                 });
1861                 Ok(())
1862         }
1863
1864         fn internal_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
1865                 let ((funding_msg, monitor_update), chan) = {
1866                         let mut channel_lock = self.channel_state.lock().unwrap();
1867                         let channel_state = channel_lock.borrow_parts();
1868                         match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
1869                                 hash_map::Entry::Occupied(mut chan) => {
1870                                         if chan.get().get_their_node_id() != *their_node_id {
1871                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1872                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1873                                         }
1874                                         (try_chan_entry!(self, chan.get_mut().funding_created(msg), channel_state, chan), chan.remove())
1875                                 },
1876                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1877                         }
1878                 };
1879                 // Because we have exclusive ownership of the channel here we can release the channel_state
1880                 // lock before add_update_monitor
1881                 if let Err(_e) = self.monitor.add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) {
1882                         unimplemented!();
1883                 }
1884                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1885                 let channel_state = channel_state_lock.borrow_parts();
1886                 match channel_state.by_id.entry(funding_msg.channel_id) {
1887                         hash_map::Entry::Occupied(_) => {
1888                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id", funding_msg.channel_id))
1889                         },
1890                         hash_map::Entry::Vacant(e) => {
1891                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
1892                                         node_id: their_node_id.clone(),
1893                                         msg: funding_msg,
1894                                 });
1895                                 e.insert(chan);
1896                         }
1897                 }
1898                 Ok(())
1899         }
1900
1901         fn internal_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
1902                 let (funding_txo, user_id) = {
1903                         let mut channel_lock = self.channel_state.lock().unwrap();
1904                         let channel_state = channel_lock.borrow_parts();
1905                         match channel_state.by_id.entry(msg.channel_id) {
1906                                 hash_map::Entry::Occupied(mut chan) => {
1907                                         if chan.get().get_their_node_id() != *their_node_id {
1908                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1909                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1910                                         }
1911                                         let chan_monitor = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
1912                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1913                                                 unimplemented!();
1914                                         }
1915                                         (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())
1916                                 },
1917                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1918                         }
1919                 };
1920                 let mut pending_events = self.pending_events.lock().unwrap();
1921                 pending_events.push(events::Event::FundingBroadcastSafe {
1922                         funding_txo: funding_txo,
1923                         user_channel_id: user_id,
1924                 });
1925                 Ok(())
1926         }
1927
1928         fn internal_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), MsgHandleErrInternal> {
1929                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1930                 let channel_state = channel_state_lock.borrow_parts();
1931                 match channel_state.by_id.entry(msg.channel_id) {
1932                         hash_map::Entry::Occupied(mut chan) => {
1933                                 if chan.get().get_their_node_id() != *their_node_id {
1934                                         //TODO: here and below MsgHandleErrInternal, #153 case
1935                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1936                                 }
1937                                 try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
1938                                 if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
1939                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
1940                                                 node_id: their_node_id.clone(),
1941                                                 msg: announcement_sigs,
1942                                         });
1943                                 }
1944                                 Ok(())
1945                         },
1946                         hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1947                 }
1948         }
1949
1950         fn internal_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
1951                 let (mut dropped_htlcs, chan_option) = {
1952                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1953                         let channel_state = channel_state_lock.borrow_parts();
1954
1955                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1956                                 hash_map::Entry::Occupied(mut chan_entry) => {
1957                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1958                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1959                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1960                                         }
1961                                         let (shutdown, closing_signed, dropped_htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg), channel_state, chan_entry);
1962                                         if let Some(msg) = shutdown {
1963                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
1964                                                         node_id: their_node_id.clone(),
1965                                                         msg,
1966                                                 });
1967                                         }
1968                                         if let Some(msg) = closing_signed {
1969                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1970                                                         node_id: their_node_id.clone(),
1971                                                         msg,
1972                                                 });
1973                                         }
1974                                         if chan_entry.get().is_shutdown() {
1975                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1976                                                         channel_state.short_to_id.remove(&short_id);
1977                                                 }
1978                                                 (dropped_htlcs, Some(chan_entry.remove_entry().1))
1979                                         } else { (dropped_htlcs, None) }
1980                                 },
1981                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1982                         }
1983                 };
1984                 for htlc_source in dropped_htlcs.drain(..) {
1985                         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() });
1986                 }
1987                 if let Some(chan) = chan_option {
1988                         if let Ok(update) = self.get_channel_update(&chan) {
1989                                 let mut channel_state = self.channel_state.lock().unwrap();
1990                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1991                                         msg: update
1992                                 });
1993                         }
1994                 }
1995                 Ok(())
1996         }
1997
1998         fn internal_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
1999                 let (tx, chan_option) = {
2000                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2001                         let channel_state = channel_state_lock.borrow_parts();
2002                         match channel_state.by_id.entry(msg.channel_id.clone()) {
2003                                 hash_map::Entry::Occupied(mut chan_entry) => {
2004                                         if chan_entry.get().get_their_node_id() != *their_node_id {
2005                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2006                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2007                                         }
2008                                         let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg), channel_state, chan_entry);
2009                                         if let Some(msg) = closing_signed {
2010                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2011                                                         node_id: their_node_id.clone(),
2012                                                         msg,
2013                                                 });
2014                                         }
2015                                         if tx.is_some() {
2016                                                 // We're done with this channel, we've got a signed closing transaction and
2017                                                 // will send the closing_signed back to the remote peer upon return. This
2018                                                 // also implies there are no pending HTLCs left on the channel, so we can
2019                                                 // fully delete it from tracking (the channel monitor is still around to
2020                                                 // watch for old state broadcasts)!
2021                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2022                                                         channel_state.short_to_id.remove(&short_id);
2023                                                 }
2024                                                 (tx, Some(chan_entry.remove_entry().1))
2025                                         } else { (tx, None) }
2026                                 },
2027                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2028                         }
2029                 };
2030                 if let Some(broadcast_tx) = tx {
2031                         self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
2032                 }
2033                 if let Some(chan) = chan_option {
2034                         if let Ok(update) = self.get_channel_update(&chan) {
2035                                 let mut channel_state = self.channel_state.lock().unwrap();
2036                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2037                                         msg: update
2038                                 });
2039                         }
2040                 }
2041                 Ok(())
2042         }
2043
2044         fn internal_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
2045                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
2046                 //determine the state of the payment based on our response/if we forward anything/the time
2047                 //we take to respond. We should take care to avoid allowing such an attack.
2048                 //
2049                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
2050                 //us repeatedly garbled in different ways, and compare our error messages, which are
2051                 //encrypted with the same key. Its not immediately obvious how to usefully exploit that,
2052                 //but we should prevent it anyway.
2053
2054                 let (mut pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
2055                 let channel_state = channel_state_lock.borrow_parts();
2056
2057                 match channel_state.by_id.entry(msg.channel_id) {
2058                         hash_map::Entry::Occupied(mut chan) => {
2059                                 if chan.get().get_their_node_id() != *their_node_id {
2060                                         //TODO: here MsgHandleErrInternal, #153 case
2061                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2062                                 }
2063                                 if !chan.get().is_usable() {
2064                                         // If the update_add is completely bogus, the call will Err and we will close,
2065                                         // but if we've sent a shutdown and they haven't acknowledged it yet, we just
2066                                         // want to reject the new HTLC and fail it backwards instead of forwarding.
2067                                         if let PendingHTLCStatus::Forward(PendingForwardHTLCInfo { incoming_shared_secret, .. }) = pending_forward_info {
2068                                                 let chan_update = self.get_channel_update(chan.get());
2069                                                 pending_forward_info = PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
2070                                                         channel_id: msg.channel_id,
2071                                                         htlc_id: msg.htlc_id,
2072                                                         reason: if let Ok(update) = chan_update {
2073                                                                 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x1000|20, &update.encode_with_len()[..])
2074                                                         } else {
2075                                                                 // This can only happen if the channel isn't in the fully-funded
2076                                                                 // state yet, implying our counterparty is trying to route payments
2077                                                                 // over the channel back to themselves (cause no one else should
2078                                                                 // know the short_id is a lightning channel yet). We should have no
2079                                                                 // problem just calling this unknown_next_peer
2080                                                                 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x4000|10, &[])
2081                                                         },
2082                                                 }));
2083                                         }
2084                                 }
2085                                 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info), channel_state, chan);
2086                         },
2087                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2088                 }
2089                 Ok(())
2090         }
2091
2092         fn internal_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
2093                 let mut channel_lock = self.channel_state.lock().unwrap();
2094                 let htlc_source = {
2095                         let channel_state = channel_lock.borrow_parts();
2096                         match channel_state.by_id.entry(msg.channel_id) {
2097                                 hash_map::Entry::Occupied(mut chan) => {
2098                                         if chan.get().get_their_node_id() != *their_node_id {
2099                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2100                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2101                                         }
2102                                         try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), channel_state, chan)
2103                                 },
2104                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2105                         }
2106                 };
2107                 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
2108                 Ok(())
2109         }
2110
2111         // Process failure we got back from upstream on a payment we sent. Returns update and a boolean
2112         // indicating that the payment itself failed
2113         fn process_onion_failure(&self, htlc_source: &HTLCSource, mut packet_decrypted: Vec<u8>) -> (Option<msgs::HTLCFailChannelUpdate>, bool) {
2114                 if let &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } = htlc_source {
2115                         macro_rules! onion_failure_log {
2116                                 ( $error_code_textual: expr, $error_code: expr, $reported_name: expr, $reported_value: expr ) => {
2117                                         log_trace!(self, "{}({:#x}) {}({})", $error_code_textual, $error_code, $reported_name, $reported_value);
2118                                 };
2119                                 ( $error_code_textual: expr, $error_code: expr ) => {
2120                                         log_trace!(self, "{}({})", $error_code_textual, $error_code);
2121                                 };
2122                         }
2123
2124                         const BADONION: u16 = 0x8000;
2125                         const PERM: u16 = 0x4000;
2126                         const UPDATE: u16 = 0x1000;
2127
2128                         let mut res = None;
2129                         let mut htlc_msat = *first_hop_htlc_msat;
2130
2131                         // Handle packed channel/node updates for passing back for the route handler
2132                         Self::construct_onion_keys_callback(&self.secp_ctx, route, session_priv, |shared_secret, _, _, route_hop| {
2133                                 if res.is_some() { return; }
2134
2135                                 let incoming_htlc_msat = htlc_msat;
2136                                 let amt_to_forward = htlc_msat - route_hop.fee_msat;
2137                                 htlc_msat = amt_to_forward;
2138
2139                                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret[..]);
2140
2141                                 let mut decryption_tmp = Vec::with_capacity(packet_decrypted.len());
2142                                 decryption_tmp.resize(packet_decrypted.len(), 0);
2143                                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
2144                                 chacha.process(&packet_decrypted, &mut decryption_tmp[..]);
2145                                 packet_decrypted = decryption_tmp;
2146
2147                                 let is_from_final_node = route.hops.last().unwrap().pubkey == route_hop.pubkey;
2148
2149                                 if let Ok(err_packet) = msgs::DecodedOnionErrorPacket::read(&mut Cursor::new(&packet_decrypted)) {
2150                                         let um = ChannelManager::gen_um_from_shared_secret(&shared_secret[..]);
2151                                         let mut hmac = Hmac::new(Sha256::new(), &um);
2152                                         hmac.input(&err_packet.encode()[32..]);
2153                                         let mut calc_tag = [0u8; 32];
2154                                         hmac.raw_result(&mut calc_tag);
2155
2156                                         if crypto::util::fixed_time_eq(&calc_tag, &err_packet.hmac) {
2157                                                 if err_packet.failuremsg.len() < 2 {
2158                                                         // Useless packet that we can't use but it passed HMAC, so it
2159                                                         // definitely came from the peer in question
2160                                                         res = Some((None, !is_from_final_node));
2161                                                 } else {
2162                                                         let error_code = byte_utils::slice_to_be16(&err_packet.failuremsg[0..2]);
2163
2164                                                         match error_code & 0xff {
2165                                                                 1|2|3 => {
2166                                                                         // either from an intermediate or final node
2167                                                                         //   invalid_realm(PERM|1),
2168                                                                         //   temporary_node_failure(NODE|2)
2169                                                                         //   permanent_node_failure(PERM|NODE|2)
2170                                                                         //   required_node_feature_mssing(PERM|NODE|3)
2171                                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2172                                                                                 node_id: route_hop.pubkey,
2173                                                                                 is_permanent: error_code & PERM == PERM,
2174                                                                         }), !(error_code & PERM == PERM && is_from_final_node)));
2175                                                                         // node returning invalid_realm is removed from network_map,
2176                                                                         // although NODE flag is not set, TODO: or remove channel only?
2177                                                                         // retry payment when removed node is not a final node
2178                                                                         return;
2179                                                                 },
2180                                                                 _ => {}
2181                                                         }
2182
2183                                                         if is_from_final_node {
2184                                                                 let payment_retryable = match error_code {
2185                                                                         c if c == PERM|15 => false, // unknown_payment_hash
2186                                                                         c if c == PERM|16 => false, // incorrect_payment_amount
2187                                                                         17 => true, // final_expiry_too_soon
2188                                                                         18 if err_packet.failuremsg.len() == 6 => { // final_incorrect_cltv_expiry
2189                                                                                 let _reported_cltv_expiry = byte_utils::slice_to_be32(&err_packet.failuremsg[2..2+4]);
2190                                                                                 true
2191                                                                         },
2192                                                                         19 if err_packet.failuremsg.len() == 10 => { // final_incorrect_htlc_amount
2193                                                                                 let _reported_incoming_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
2194                                                                                 true
2195                                                                         },
2196                                                                         _ => {
2197                                                                                 // A final node has sent us either an invalid code or an error_code that
2198                                                                                 // MUST be sent from the processing node, or the formmat of failuremsg
2199                                                                                 // does not coform to the spec.
2200                                                                                 // Remove it from the network map and don't may retry payment
2201                                                                                 res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2202                                                                                         node_id: route_hop.pubkey,
2203                                                                                         is_permanent: true,
2204                                                                                 }), false));
2205                                                                                 return;
2206                                                                         }
2207                                                                 };
2208                                                                 res = Some((None, payment_retryable));
2209                                                                 return;
2210                                                         }
2211
2212                                                         // now, error_code should be only from the intermediate nodes
2213                                                         match error_code {
2214                                                                 _c if error_code & PERM == PERM => {
2215                                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
2216                                                                                 short_channel_id: route_hop.short_channel_id,
2217                                                                                 is_permanent: true,
2218                                                                         }), false));
2219                                                                 },
2220                                                                 _c if error_code & UPDATE == UPDATE => {
2221                                                                         let offset = match error_code {
2222                                                                                 c if c == UPDATE|7  => 0, // temporary_channel_failure
2223                                                                                 c if c == UPDATE|11 => 8, // amount_below_minimum
2224                                                                                 c if c == UPDATE|12 => 8, // fee_insufficient
2225                                                                                 c if c == UPDATE|13 => 4, // incorrect_cltv_expiry
2226                                                                                 c if c == UPDATE|14 => 0, // expiry_too_soon
2227                                                                                 c if c == UPDATE|20 => 2, // channel_disabled
2228                                                                                 _ =>  {
2229                                                                                         // node sending unknown code
2230                                                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2231                                                                                                 node_id: route_hop.pubkey,
2232                                                                                                 is_permanent: true,
2233                                                                                         }), false));
2234                                                                                         return;
2235                                                                                 }
2236                                                                         };
2237
2238                                                                         if err_packet.failuremsg.len() >= offset + 2 {
2239                                                                                 let update_len = byte_utils::slice_to_be16(&err_packet.failuremsg[offset+2..offset+4]) as usize;
2240                                                                                 if err_packet.failuremsg.len() >= offset + 4 + update_len {
2241                                                                                         if let Ok(chan_update) = msgs::ChannelUpdate::read(&mut Cursor::new(&err_packet.failuremsg[offset + 4..offset + 4 + update_len])) {
2242                                                                                                 // if channel_update should NOT have caused the failure:
2243                                                                                                 // MAY treat the channel_update as invalid.
2244                                                                                                 let is_chan_update_invalid = match error_code {
2245                                                                                                         c if c == UPDATE|7 => { // temporary_channel_failure
2246                                                                                                                 false
2247                                                                                                         },
2248                                                                                                         c if c == UPDATE|11 => { // amount_below_minimum
2249                                                                                                                 let reported_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
2250                                                                                                                 onion_failure_log!("amount_below_minimum", UPDATE|11, "htlc_msat", reported_htlc_msat);
2251                                                                                                                 incoming_htlc_msat > chan_update.contents.htlc_minimum_msat
2252                                                                                                         },
2253                                                                                                         c if c == UPDATE|12 => { // fee_insufficient
2254                                                                                                                 let reported_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
2255                                                                                                                 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) });
2256                                                                                                                 onion_failure_log!("fee_insufficient", UPDATE|12, "htlc_msat", reported_htlc_msat);
2257                                                                                                                 new_fee.is_none() || incoming_htlc_msat >= new_fee.unwrap() && incoming_htlc_msat >= amt_to_forward + new_fee.unwrap()
2258                                                                                                         }
2259                                                                                                         c if c == UPDATE|13 => { // incorrect_cltv_expiry
2260                                                                                                                 let reported_cltv_expiry = byte_utils::slice_to_be32(&err_packet.failuremsg[2..2+4]);
2261                                                                                                                 onion_failure_log!("incorrect_cltv_expiry", UPDATE|13, "cltv_expiry", reported_cltv_expiry);
2262                                                                                                                 route_hop.cltv_expiry_delta as u16 >= chan_update.contents.cltv_expiry_delta
2263                                                                                                         },
2264                                                                                                         c if c == UPDATE|20 => { // channel_disabled
2265                                                                                                                 let reported_flags = byte_utils::slice_to_be16(&err_packet.failuremsg[2..2+2]);
2266                                                                                                                 onion_failure_log!("channel_disabled", UPDATE|20, "flags", reported_flags);
2267                                                                                                                 chan_update.contents.flags & 0x01 == 0x01
2268                                                                                                         },
2269                                                                                                         c if c == UPDATE|21 => true, // expiry_too_far
2270                                                                                                         _ => { unreachable!(); },
2271                                                                                                 };
2272
2273                                                                                                 let msg = if is_chan_update_invalid { None } else {
2274                                                                                                         Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {
2275                                                                                                                 msg: chan_update,
2276                                                                                                         })
2277                                                                                                 };
2278                                                                                                 res = Some((msg, true));
2279                                                                                                 return;
2280                                                                                         }
2281                                                                                 }
2282                                                                         }
2283                                                                 },
2284                                                                 _c if error_code & BADONION == BADONION => {
2285                                                                         //TODO
2286                                                                 },
2287                                                                 14 => { // expiry_too_soon
2288                                                                         res = Some((None, true));
2289                                                                         return;
2290                                                                 }
2291                                                                 _ => {
2292                                                                         // node sending unknown code
2293                                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2294                                                                                 node_id: route_hop.pubkey,
2295                                                                                 is_permanent: true,
2296                                                                         }), false));
2297                                                                         return;
2298                                                                 }
2299                                                         }
2300                                                 }
2301                                         }
2302                                 }
2303                         }).expect("Route that we sent via spontaneously grew invalid keys in the middle of it?");
2304                         res.unwrap_or((None, true))
2305                 } else { ((None, true)) }
2306         }
2307
2308         fn internal_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
2309                 let mut channel_lock = self.channel_state.lock().unwrap();
2310                 let channel_state = channel_lock.borrow_parts();
2311                 match channel_state.by_id.entry(msg.channel_id) {
2312                         hash_map::Entry::Occupied(mut chan) => {
2313                                 if chan.get().get_their_node_id() != *their_node_id {
2314                                         //TODO: here and below MsgHandleErrInternal, #153 case
2315                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2316                                 }
2317                                 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::ErrorPacket { err: msg.reason.clone() }), channel_state, chan);
2318                         },
2319                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2320                 }
2321                 Ok(())
2322         }
2323
2324         fn internal_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
2325                 let mut channel_lock = self.channel_state.lock().unwrap();
2326                 let channel_state = channel_lock.borrow_parts();
2327                 match channel_state.by_id.entry(msg.channel_id) {
2328                         hash_map::Entry::Occupied(mut chan) => {
2329                                 if chan.get().get_their_node_id() != *their_node_id {
2330                                         //TODO: here and below MsgHandleErrInternal, #153 case
2331                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2332                                 }
2333                                 if (msg.failure_code & 0x8000) == 0 {
2334                                         try_chan_entry!(self, Err(ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set")), channel_state, chan);
2335                                 }
2336                                 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);
2337                                 Ok(())
2338                         },
2339                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2340                 }
2341         }
2342
2343         fn internal_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
2344                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2345                 let channel_state = channel_state_lock.borrow_parts();
2346                 match channel_state.by_id.entry(msg.channel_id) {
2347                         hash_map::Entry::Occupied(mut chan) => {
2348                                 if chan.get().get_their_node_id() != *their_node_id {
2349                                         //TODO: here and below MsgHandleErrInternal, #153 case
2350                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2351                                 }
2352                                 let (revoke_and_ack, commitment_signed, closing_signed, chan_monitor) =
2353                                         try_chan_entry!(self, chan.get_mut().commitment_signed(&msg, &*self.fee_estimator), channel_state, chan);
2354                                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2355                                         return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, commitment_signed.is_some());
2356                                         //TODO: Rebroadcast closing_signed if present on monitor update restoration
2357                                 }
2358                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2359                                         node_id: their_node_id.clone(),
2360                                         msg: revoke_and_ack,
2361                                 });
2362                                 if let Some(msg) = commitment_signed {
2363                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2364                                                 node_id: their_node_id.clone(),
2365                                                 updates: msgs::CommitmentUpdate {
2366                                                         update_add_htlcs: Vec::new(),
2367                                                         update_fulfill_htlcs: Vec::new(),
2368                                                         update_fail_htlcs: Vec::new(),
2369                                                         update_fail_malformed_htlcs: Vec::new(),
2370                                                         update_fee: None,
2371                                                         commitment_signed: msg,
2372                                                 },
2373                                         });
2374                                 }
2375                                 if let Some(msg) = closing_signed {
2376                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2377                                                 node_id: their_node_id.clone(),
2378                                                 msg,
2379                                         });
2380                                 }
2381                                 Ok(())
2382                         },
2383                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2384                 }
2385         }
2386
2387         #[inline]
2388         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64)>)]) {
2389                 for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
2390                         let mut forward_event = None;
2391                         if !pending_forwards.is_empty() {
2392                                 let mut channel_state = self.channel_state.lock().unwrap();
2393                                 if channel_state.forward_htlcs.is_empty() {
2394                                         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));
2395                                         channel_state.next_forward = forward_event.unwrap();
2396                                 }
2397                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2398                                         match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
2399                                                 hash_map::Entry::Occupied(mut entry) => {
2400                                                         entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info });
2401                                                 },
2402                                                 hash_map::Entry::Vacant(entry) => {
2403                                                         entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info }));
2404                                                 }
2405                                         }
2406                                 }
2407                         }
2408                         match forward_event {
2409                                 Some(time) => {
2410                                         let mut pending_events = self.pending_events.lock().unwrap();
2411                                         pending_events.push(events::Event::PendingHTLCsForwardable {
2412                                                 time_forwardable: time
2413                                         });
2414                                 }
2415                                 None => {},
2416                         }
2417                 }
2418         }
2419
2420         fn internal_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
2421                 let (pending_forwards, mut pending_failures, short_channel_id) = {
2422                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2423                         let channel_state = channel_state_lock.borrow_parts();
2424                         match channel_state.by_id.entry(msg.channel_id) {
2425                                 hash_map::Entry::Occupied(mut chan) => {
2426                                         if chan.get().get_their_node_id() != *their_node_id {
2427                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2428                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2429                                         }
2430                                         let (commitment_update, pending_forwards, pending_failures, closing_signed, chan_monitor) =
2431                                                 try_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &*self.fee_estimator), channel_state, chan);
2432                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2433                                                 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, pending_forwards, pending_failures);
2434                                         }
2435                                         if let Some(updates) = commitment_update {
2436                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2437                                                         node_id: their_node_id.clone(),
2438                                                         updates,
2439                                                 });
2440                                         }
2441                                         if let Some(msg) = closing_signed {
2442                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2443                                                         node_id: their_node_id.clone(),
2444                                                         msg,
2445                                                 });
2446                                         }
2447                                         (pending_forwards, pending_failures, chan.get().get_short_channel_id().expect("RAA should only work on a short-id-available channel"))
2448                                 },
2449                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2450                         }
2451                 };
2452                 for failure in pending_failures.drain(..) {
2453                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2454                 }
2455                 self.forward_htlcs(&mut [(short_channel_id, pending_forwards)]);
2456
2457                 Ok(())
2458         }
2459
2460         fn internal_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2461                 let mut channel_lock = self.channel_state.lock().unwrap();
2462                 let channel_state = channel_lock.borrow_parts();
2463                 match channel_state.by_id.entry(msg.channel_id) {
2464                         hash_map::Entry::Occupied(mut chan) => {
2465                                 if chan.get().get_their_node_id() != *their_node_id {
2466                                         //TODO: here and below MsgHandleErrInternal, #153 case
2467                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2468                                 }
2469                                 try_chan_entry!(self, chan.get_mut().update_fee(&*self.fee_estimator, &msg), channel_state, chan);
2470                         },
2471                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2472                 }
2473                 Ok(())
2474         }
2475
2476         fn internal_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2477                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2478                 let channel_state = channel_state_lock.borrow_parts();
2479
2480                 match channel_state.by_id.entry(msg.channel_id) {
2481                         hash_map::Entry::Occupied(mut chan) => {
2482                                 if chan.get().get_their_node_id() != *their_node_id {
2483                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2484                                 }
2485                                 if !chan.get().is_usable() {
2486                                         return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Got an announcement_signatures before we were ready for it", action: Some(msgs::ErrorAction::IgnoreError)}));
2487                                 }
2488
2489                                 let our_node_id = self.get_our_node_id();
2490                                 let (announcement, our_bitcoin_sig) =
2491                                         try_chan_entry!(self, chan.get_mut().get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone()), channel_state, chan);
2492
2493                                 let were_node_one = announcement.node_id_1 == our_node_id;
2494                                 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
2495                                 if self.secp_ctx.verify(&msghash, &msg.node_signature, if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 }).is_err() ||
2496                                                 self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 }).is_err() {
2497                                         try_chan_entry!(self, Err(ChannelError::Close("Bad announcement_signatures node_signature")), channel_state, chan);
2498                                 }
2499
2500                                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2501
2502                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
2503                                         msg: msgs::ChannelAnnouncement {
2504                                                 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
2505                                                 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
2506                                                 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
2507                                                 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
2508                                                 contents: announcement,
2509                                         },
2510                                         update_msg: self.get_channel_update(chan.get()).unwrap(), // can only fail if we're not in a ready state
2511                                 });
2512                         },
2513                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2514                 }
2515                 Ok(())
2516         }
2517
2518         fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
2519                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2520                 let channel_state = channel_state_lock.borrow_parts();
2521
2522                 match channel_state.by_id.entry(msg.channel_id) {
2523                         hash_map::Entry::Occupied(mut chan) => {
2524                                 if chan.get().get_their_node_id() != *their_node_id {
2525                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2526                                 }
2527                                 let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, mut order, shutdown) =
2528                                         try_chan_entry!(self, chan.get_mut().channel_reestablish(msg), channel_state, chan);
2529                                 if let Some(monitor) = channel_monitor {
2530                                         if let Err(e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
2531                                                 // channel_reestablish doesn't guarantee the order it returns is sensical
2532                                                 // for the messages it returns, but if we're setting what messages to
2533                                                 // re-transmit on monitor update success, we need to make sure it is sane.
2534                                                 if revoke_and_ack.is_none() {
2535                                                         order = RAACommitmentOrder::CommitmentFirst;
2536                                                 }
2537                                                 if commitment_update.is_none() {
2538                                                         order = RAACommitmentOrder::RevokeAndACKFirst;
2539                                                 }
2540                                                 return_monitor_err!(self, e, channel_state, chan, order);
2541                                                 //TODO: Resend the funding_locked if needed once we get the monitor running again
2542                                         }
2543                                 }
2544                                 if let Some(msg) = funding_locked {
2545                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2546                                                 node_id: their_node_id.clone(),
2547                                                 msg
2548                                         });
2549                                 }
2550                                 macro_rules! send_raa { () => {
2551                                         if let Some(msg) = revoke_and_ack {
2552                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2553                                                         node_id: their_node_id.clone(),
2554                                                         msg
2555                                                 });
2556                                         }
2557                                 } }
2558                                 macro_rules! send_cu { () => {
2559                                         if let Some(updates) = commitment_update {
2560                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2561                                                         node_id: their_node_id.clone(),
2562                                                         updates
2563                                                 });
2564                                         }
2565                                 } }
2566                                 match order {
2567                                         RAACommitmentOrder::RevokeAndACKFirst => {
2568                                                 send_raa!();
2569                                                 send_cu!();
2570                                         },
2571                                         RAACommitmentOrder::CommitmentFirst => {
2572                                                 send_cu!();
2573                                                 send_raa!();
2574                                         },
2575                                 }
2576                                 if let Some(msg) = shutdown {
2577                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2578                                                 node_id: their_node_id.clone(),
2579                                                 msg,
2580                                         });
2581                                 }
2582                                 Ok(())
2583                         },
2584                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2585                 }
2586         }
2587
2588         /// Begin Update fee process. Allowed only on an outbound channel.
2589         /// If successful, will generate a UpdateHTLCs event, so you should probably poll
2590         /// PeerManager::process_events afterwards.
2591         /// Note: This API is likely to change!
2592         #[doc(hidden)]
2593         pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u64) -> Result<(), APIError> {
2594                 let _ = self.total_consistency_lock.read().unwrap();
2595                 let their_node_id;
2596                 let err: Result<(), _> = loop {
2597                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2598                         let channel_state = channel_state_lock.borrow_parts();
2599
2600                         match channel_state.by_id.entry(channel_id) {
2601                                 hash_map::Entry::Vacant(_) => return Err(APIError::APIMisuseError{err: "Failed to find corresponding channel"}),
2602                                 hash_map::Entry::Occupied(mut chan) => {
2603                                         if !chan.get().is_outbound() {
2604                                                 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel"});
2605                                         }
2606                                         if chan.get().is_awaiting_monitor_update() {
2607                                                 return Err(APIError::MonitorUpdateFailed);
2608                                         }
2609                                         if !chan.get().is_live() {
2610                                                 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected"});
2611                                         }
2612                                         their_node_id = chan.get().get_their_node_id();
2613                                         if let Some((update_fee, commitment_signed, chan_monitor)) =
2614                                                         break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw), channel_state, chan)
2615                                         {
2616                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2617                                                         unimplemented!();
2618                                                 }
2619                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2620                                                         node_id: chan.get().get_their_node_id(),
2621                                                         updates: msgs::CommitmentUpdate {
2622                                                                 update_add_htlcs: Vec::new(),
2623                                                                 update_fulfill_htlcs: Vec::new(),
2624                                                                 update_fail_htlcs: Vec::new(),
2625                                                                 update_fail_malformed_htlcs: Vec::new(),
2626                                                                 update_fee: Some(update_fee),
2627                                                                 commitment_signed,
2628                                                         },
2629                                                 });
2630                                         }
2631                                 },
2632                         }
2633                         return Ok(())
2634                 };
2635
2636                 match handle_error!(self, err, their_node_id) {
2637                         Ok(_) => unreachable!(),
2638                         Err(e) => {
2639                                 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
2640                                 } else {
2641                                         log_error!(self, "Got bad keys: {}!", e.err);
2642                                         let mut channel_state = self.channel_state.lock().unwrap();
2643                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
2644                                                 node_id: their_node_id,
2645                                                 action: e.action,
2646                                         });
2647                                 }
2648                                 Err(APIError::APIMisuseError { err: e.err })
2649                         },
2650                 }
2651         }
2652 }
2653
2654 impl events::MessageSendEventsProvider for ChannelManager {
2655         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
2656                 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2657                 // user to serialize a ChannelManager with pending events in it and lose those events on
2658                 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2659                 {
2660                         //TODO: This behavior should be documented.
2661                         for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2662                                 if let Some(preimage) = htlc_update.payment_preimage {
2663                                         log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2664                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2665                                 } else {
2666                                         log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2667                                         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() });
2668                                 }
2669                         }
2670                 }
2671
2672                 let mut ret = Vec::new();
2673                 let mut channel_state = self.channel_state.lock().unwrap();
2674                 mem::swap(&mut ret, &mut channel_state.pending_msg_events);
2675                 ret
2676         }
2677 }
2678
2679 impl events::EventsProvider for ChannelManager {
2680         fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
2681                 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2682                 // user to serialize a ChannelManager with pending events in it and lose those events on
2683                 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2684                 {
2685                         //TODO: This behavior should be documented.
2686                         for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2687                                 if let Some(preimage) = htlc_update.payment_preimage {
2688                                         log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2689                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2690                                 } else {
2691                                         log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2692                                         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() });
2693                                 }
2694                         }
2695                 }
2696
2697                 let mut ret = Vec::new();
2698                 let mut pending_events = self.pending_events.lock().unwrap();
2699                 mem::swap(&mut ret, &mut *pending_events);
2700                 ret
2701         }
2702 }
2703
2704 impl ChainListener for ChannelManager {
2705         fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
2706                 let header_hash = header.bitcoin_hash();
2707                 log_trace!(self, "Block {} at height {} connected with {} txn matched", header_hash, height, txn_matched.len());
2708                 let _ = self.total_consistency_lock.read().unwrap();
2709                 let mut failed_channels = Vec::new();
2710                 {
2711                         let mut channel_lock = self.channel_state.lock().unwrap();
2712                         let channel_state = channel_lock.borrow_parts();
2713                         let short_to_id = channel_state.short_to_id;
2714                         let pending_msg_events = channel_state.pending_msg_events;
2715                         channel_state.by_id.retain(|_, channel| {
2716                                 let chan_res = channel.block_connected(header, height, txn_matched, indexes_of_txn_matched);
2717                                 if let Ok(Some(funding_locked)) = chan_res {
2718                                         pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2719                                                 node_id: channel.get_their_node_id(),
2720                                                 msg: funding_locked,
2721                                         });
2722                                         if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
2723                                                 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2724                                                         node_id: channel.get_their_node_id(),
2725                                                         msg: announcement_sigs,
2726                                                 });
2727                                         }
2728                                         short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
2729                                 } else if let Err(e) = chan_res {
2730                                         pending_msg_events.push(events::MessageSendEvent::HandleError {
2731                                                 node_id: channel.get_their_node_id(),
2732                                                 action: Some(msgs::ErrorAction::SendErrorMessage { msg: e }),
2733                                         });
2734                                         return false;
2735                                 }
2736                                 if let Some(funding_txo) = channel.get_funding_txo() {
2737                                         for tx in txn_matched {
2738                                                 for inp in tx.input.iter() {
2739                                                         if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
2740                                                                 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()));
2741                                                                 if let Some(short_id) = channel.get_short_channel_id() {
2742                                                                         short_to_id.remove(&short_id);
2743                                                                 }
2744                                                                 // It looks like our counterparty went on-chain. We go ahead and
2745                                                                 // broadcast our latest local state as well here, just in case its
2746                                                                 // some kind of SPV attack, though we expect these to be dropped.
2747                                                                 failed_channels.push(channel.force_shutdown());
2748                                                                 if let Ok(update) = self.get_channel_update(&channel) {
2749                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2750                                                                                 msg: update
2751                                                                         });
2752                                                                 }
2753                                                                 return false;
2754                                                         }
2755                                                 }
2756                                         }
2757                                 }
2758                                 if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height) {
2759                                         if let Some(short_id) = channel.get_short_channel_id() {
2760                                                 short_to_id.remove(&short_id);
2761                                         }
2762                                         failed_channels.push(channel.force_shutdown());
2763                                         // If would_broadcast_at_height() is true, the channel_monitor will broadcast
2764                                         // the latest local tx for us, so we should skip that here (it doesn't really
2765                                         // hurt anything, but does make tests a bit simpler).
2766                                         failed_channels.last_mut().unwrap().0 = Vec::new();
2767                                         if let Ok(update) = self.get_channel_update(&channel) {
2768                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2769                                                         msg: update
2770                                                 });
2771                                         }
2772                                         return false;
2773                                 }
2774                                 true
2775                         });
2776                 }
2777                 for failure in failed_channels.drain(..) {
2778                         self.finish_force_close_channel(failure);
2779                 }
2780                 self.latest_block_height.store(height as usize, Ordering::Release);
2781                 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header_hash;
2782         }
2783
2784         /// We force-close the channel without letting our counterparty participate in the shutdown
2785         fn block_disconnected(&self, header: &BlockHeader) {
2786                 let _ = self.total_consistency_lock.read().unwrap();
2787                 let mut failed_channels = Vec::new();
2788                 {
2789                         let mut channel_lock = self.channel_state.lock().unwrap();
2790                         let channel_state = channel_lock.borrow_parts();
2791                         let short_to_id = channel_state.short_to_id;
2792                         let pending_msg_events = channel_state.pending_msg_events;
2793                         channel_state.by_id.retain(|_,  v| {
2794                                 if v.block_disconnected(header) {
2795                                         if let Some(short_id) = v.get_short_channel_id() {
2796                                                 short_to_id.remove(&short_id);
2797                                         }
2798                                         failed_channels.push(v.force_shutdown());
2799                                         if let Ok(update) = self.get_channel_update(&v) {
2800                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2801                                                         msg: update
2802                                                 });
2803                                         }
2804                                         false
2805                                 } else {
2806                                         true
2807                                 }
2808                         });
2809                 }
2810                 for failure in failed_channels.drain(..) {
2811                         self.finish_force_close_channel(failure);
2812                 }
2813                 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
2814                 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
2815         }
2816 }
2817
2818 impl ChannelMessageHandler for ChannelManager {
2819         //TODO: Handle errors and close channel (or so)
2820         fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), HandleError> {
2821                 let _ = self.total_consistency_lock.read().unwrap();
2822                 handle_error!(self, self.internal_open_channel(their_node_id, msg), their_node_id)
2823         }
2824
2825         fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), HandleError> {
2826                 let _ = self.total_consistency_lock.read().unwrap();
2827                 handle_error!(self, self.internal_accept_channel(their_node_id, msg), their_node_id)
2828         }
2829
2830         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), HandleError> {
2831                 let _ = self.total_consistency_lock.read().unwrap();
2832                 handle_error!(self, self.internal_funding_created(their_node_id, msg), their_node_id)
2833         }
2834
2835         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), HandleError> {
2836                 let _ = self.total_consistency_lock.read().unwrap();
2837                 handle_error!(self, self.internal_funding_signed(their_node_id, msg), their_node_id)
2838         }
2839
2840         fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), HandleError> {
2841                 let _ = self.total_consistency_lock.read().unwrap();
2842                 handle_error!(self, self.internal_funding_locked(their_node_id, msg), their_node_id)
2843         }
2844
2845         fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), HandleError> {
2846                 let _ = self.total_consistency_lock.read().unwrap();
2847                 handle_error!(self, self.internal_shutdown(their_node_id, msg), their_node_id)
2848         }
2849
2850         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), HandleError> {
2851                 let _ = self.total_consistency_lock.read().unwrap();
2852                 handle_error!(self, self.internal_closing_signed(their_node_id, msg), their_node_id)
2853         }
2854
2855         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), msgs::HandleError> {
2856                 let _ = self.total_consistency_lock.read().unwrap();
2857                 handle_error!(self, self.internal_update_add_htlc(their_node_id, msg), their_node_id)
2858         }
2859
2860         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), HandleError> {
2861                 let _ = self.total_consistency_lock.read().unwrap();
2862                 handle_error!(self, self.internal_update_fulfill_htlc(their_node_id, msg), their_node_id)
2863         }
2864
2865         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), HandleError> {
2866                 let _ = self.total_consistency_lock.read().unwrap();
2867                 handle_error!(self, self.internal_update_fail_htlc(their_node_id, msg), their_node_id)
2868         }
2869
2870         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), HandleError> {
2871                 let _ = self.total_consistency_lock.read().unwrap();
2872                 handle_error!(self, self.internal_update_fail_malformed_htlc(their_node_id, msg), their_node_id)
2873         }
2874
2875         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), HandleError> {
2876                 let _ = self.total_consistency_lock.read().unwrap();
2877                 handle_error!(self, self.internal_commitment_signed(their_node_id, msg), their_node_id)
2878         }
2879
2880         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), HandleError> {
2881                 let _ = self.total_consistency_lock.read().unwrap();
2882                 handle_error!(self, self.internal_revoke_and_ack(their_node_id, msg), their_node_id)
2883         }
2884
2885         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), HandleError> {
2886                 let _ = self.total_consistency_lock.read().unwrap();
2887                 handle_error!(self, self.internal_update_fee(their_node_id, msg), their_node_id)
2888         }
2889
2890         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), HandleError> {
2891                 let _ = self.total_consistency_lock.read().unwrap();
2892                 handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
2893         }
2894
2895         fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), HandleError> {
2896                 let _ = self.total_consistency_lock.read().unwrap();
2897                 handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), their_node_id)
2898         }
2899
2900         fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
2901                 let _ = self.total_consistency_lock.read().unwrap();
2902                 let mut failed_channels = Vec::new();
2903                 let mut failed_payments = Vec::new();
2904                 {
2905                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2906                         let channel_state = channel_state_lock.borrow_parts();
2907                         let short_to_id = channel_state.short_to_id;
2908                         let pending_msg_events = channel_state.pending_msg_events;
2909                         if no_connection_possible {
2910                                 log_debug!(self, "Failing all channels with {} due to no_connection_possible", log_pubkey!(their_node_id));
2911                                 channel_state.by_id.retain(|_, chan| {
2912                                         if chan.get_their_node_id() == *their_node_id {
2913                                                 if let Some(short_id) = chan.get_short_channel_id() {
2914                                                         short_to_id.remove(&short_id);
2915                                                 }
2916                                                 failed_channels.push(chan.force_shutdown());
2917                                                 if let Ok(update) = self.get_channel_update(&chan) {
2918                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2919                                                                 msg: update
2920                                                         });
2921                                                 }
2922                                                 false
2923                                         } else {
2924                                                 true
2925                                         }
2926                                 });
2927                         } else {
2928                                 log_debug!(self, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(their_node_id));
2929                                 channel_state.by_id.retain(|_, chan| {
2930                                         if chan.get_their_node_id() == *their_node_id {
2931                                                 //TODO: mark channel disabled (and maybe announce such after a timeout).
2932                                                 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused();
2933                                                 if !failed_adds.is_empty() {
2934                                                         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
2935                                                         failed_payments.push((chan_update, failed_adds));
2936                                                 }
2937                                                 if chan.is_shutdown() {
2938                                                         if let Some(short_id) = chan.get_short_channel_id() {
2939                                                                 short_to_id.remove(&short_id);
2940                                                         }
2941                                                         return false;
2942                                                 }
2943                                         }
2944                                         true
2945                                 })
2946                         }
2947                 }
2948                 for failure in failed_channels.drain(..) {
2949                         self.finish_force_close_channel(failure);
2950                 }
2951                 for (chan_update, mut htlc_sources) in failed_payments {
2952                         for (htlc_source, payment_hash) in htlc_sources.drain(..) {
2953                                 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
2954                         }
2955                 }
2956         }
2957
2958         fn peer_connected(&self, their_node_id: &PublicKey) {
2959                 log_debug!(self, "Generating channel_reestablish events for {}", log_pubkey!(their_node_id));
2960
2961                 let _ = self.total_consistency_lock.read().unwrap();
2962                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2963                 let channel_state = channel_state_lock.borrow_parts();
2964                 let pending_msg_events = channel_state.pending_msg_events;
2965                 channel_state.by_id.retain(|_, chan| {
2966                         if chan.get_their_node_id() == *their_node_id {
2967                                 if !chan.have_received_message() {
2968                                         // If we created this (outbound) channel while we were disconnected from the
2969                                         // peer we probably failed to send the open_channel message, which is now
2970                                         // lost. We can't have had anything pending related to this channel, so we just
2971                                         // drop it.
2972                                         false
2973                                 } else {
2974                                         pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
2975                                                 node_id: chan.get_their_node_id(),
2976                                                 msg: chan.get_channel_reestablish(),
2977                                         });
2978                                         true
2979                                 }
2980                         } else { true }
2981                 });
2982                 //TODO: Also re-broadcast announcement_signatures
2983         }
2984
2985         fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
2986                 let _ = self.total_consistency_lock.read().unwrap();
2987
2988                 if msg.channel_id == [0; 32] {
2989                         for chan in self.list_channels() {
2990                                 if chan.remote_network_id == *their_node_id {
2991                                         self.force_close_channel(&chan.channel_id);
2992                                 }
2993                         }
2994                 } else {
2995                         self.force_close_channel(&msg.channel_id);
2996                 }
2997         }
2998 }
2999
3000 const SERIALIZATION_VERSION: u8 = 1;
3001 const MIN_SERIALIZATION_VERSION: u8 = 1;
3002
3003 impl Writeable for PendingForwardHTLCInfo {
3004         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3005                 if let &Some(ref onion) = &self.onion_packet {
3006                         1u8.write(writer)?;
3007                         onion.write(writer)?;
3008                 } else {
3009                         0u8.write(writer)?;
3010                 }
3011                 self.incoming_shared_secret.write(writer)?;
3012                 self.payment_hash.write(writer)?;
3013                 self.short_channel_id.write(writer)?;
3014                 self.amt_to_forward.write(writer)?;
3015                 self.outgoing_cltv_value.write(writer)?;
3016                 Ok(())
3017         }
3018 }
3019
3020 impl<R: ::std::io::Read> Readable<R> for PendingForwardHTLCInfo {
3021         fn read(reader: &mut R) -> Result<PendingForwardHTLCInfo, DecodeError> {
3022                 let onion_packet = match <u8 as Readable<R>>::read(reader)? {
3023                         0 => None,
3024                         1 => Some(msgs::OnionPacket::read(reader)?),
3025                         _ => return Err(DecodeError::InvalidValue),
3026                 };
3027                 Ok(PendingForwardHTLCInfo {
3028                         onion_packet,
3029                         incoming_shared_secret: Readable::read(reader)?,
3030                         payment_hash: Readable::read(reader)?,
3031                         short_channel_id: Readable::read(reader)?,
3032                         amt_to_forward: Readable::read(reader)?,
3033                         outgoing_cltv_value: Readable::read(reader)?,
3034                 })
3035         }
3036 }
3037
3038 impl Writeable for HTLCFailureMsg {
3039         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3040                 match self {
3041                         &HTLCFailureMsg::Relay(ref fail_msg) => {
3042                                 0u8.write(writer)?;
3043                                 fail_msg.write(writer)?;
3044                         },
3045                         &HTLCFailureMsg::Malformed(ref fail_msg) => {
3046                                 1u8.write(writer)?;
3047                                 fail_msg.write(writer)?;
3048                         }
3049                 }
3050                 Ok(())
3051         }
3052 }
3053
3054 impl<R: ::std::io::Read> Readable<R> for HTLCFailureMsg {
3055         fn read(reader: &mut R) -> Result<HTLCFailureMsg, DecodeError> {
3056                 match <u8 as Readable<R>>::read(reader)? {
3057                         0 => Ok(HTLCFailureMsg::Relay(Readable::read(reader)?)),
3058                         1 => Ok(HTLCFailureMsg::Malformed(Readable::read(reader)?)),
3059                         _ => Err(DecodeError::InvalidValue),
3060                 }
3061         }
3062 }
3063
3064 impl Writeable for PendingHTLCStatus {
3065         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3066                 match self {
3067                         &PendingHTLCStatus::Forward(ref forward_info) => {
3068                                 0u8.write(writer)?;
3069                                 forward_info.write(writer)?;
3070                         },
3071                         &PendingHTLCStatus::Fail(ref fail_msg) => {
3072                                 1u8.write(writer)?;
3073                                 fail_msg.write(writer)?;
3074                         }
3075                 }
3076                 Ok(())
3077         }
3078 }
3079
3080 impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
3081         fn read(reader: &mut R) -> Result<PendingHTLCStatus, DecodeError> {
3082                 match <u8 as Readable<R>>::read(reader)? {
3083                         0 => Ok(PendingHTLCStatus::Forward(Readable::read(reader)?)),
3084                         1 => Ok(PendingHTLCStatus::Fail(Readable::read(reader)?)),
3085                         _ => Err(DecodeError::InvalidValue),
3086                 }
3087         }
3088 }
3089
3090 impl_writeable!(HTLCPreviousHopData, 0, {
3091         short_channel_id,
3092         htlc_id,
3093         incoming_packet_shared_secret
3094 });
3095
3096 impl Writeable for HTLCSource {
3097         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3098                 match self {
3099                         &HTLCSource::PreviousHopData(ref hop_data) => {
3100                                 0u8.write(writer)?;
3101                                 hop_data.write(writer)?;
3102                         },
3103                         &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } => {
3104                                 1u8.write(writer)?;
3105                                 route.write(writer)?;
3106                                 session_priv.write(writer)?;
3107                                 first_hop_htlc_msat.write(writer)?;
3108                         }
3109                 }
3110                 Ok(())
3111         }
3112 }
3113
3114 impl<R: ::std::io::Read> Readable<R> for HTLCSource {
3115         fn read(reader: &mut R) -> Result<HTLCSource, DecodeError> {
3116                 match <u8 as Readable<R>>::read(reader)? {
3117                         0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
3118                         1 => Ok(HTLCSource::OutboundRoute {
3119                                 route: Readable::read(reader)?,
3120                                 session_priv: Readable::read(reader)?,
3121                                 first_hop_htlc_msat: Readable::read(reader)?,
3122                         }),
3123                         _ => Err(DecodeError::InvalidValue),
3124                 }
3125         }
3126 }
3127
3128 impl Writeable for HTLCFailReason {
3129         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3130                 match self {
3131                         &HTLCFailReason::ErrorPacket { ref err } => {
3132                                 0u8.write(writer)?;
3133                                 err.write(writer)?;
3134                         },
3135                         &HTLCFailReason::Reason { ref failure_code, ref data } => {
3136                                 1u8.write(writer)?;
3137                                 failure_code.write(writer)?;
3138                                 data.write(writer)?;
3139                         }
3140                 }
3141                 Ok(())
3142         }
3143 }
3144
3145 impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
3146         fn read(reader: &mut R) -> Result<HTLCFailReason, DecodeError> {
3147                 match <u8 as Readable<R>>::read(reader)? {
3148                         0 => Ok(HTLCFailReason::ErrorPacket { err: Readable::read(reader)? }),
3149                         1 => Ok(HTLCFailReason::Reason {
3150                                 failure_code: Readable::read(reader)?,
3151                                 data: Readable::read(reader)?,
3152                         }),
3153                         _ => Err(DecodeError::InvalidValue),
3154                 }
3155         }
3156 }
3157
3158 impl_writeable!(HTLCForwardInfo, 0, {
3159         prev_short_channel_id,
3160         prev_htlc_id,
3161         forward_info
3162 });
3163
3164 impl Writeable for ChannelManager {
3165         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3166                 let _ = self.total_consistency_lock.write().unwrap();
3167
3168                 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
3169                 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
3170
3171                 self.genesis_hash.write(writer)?;
3172                 (self.latest_block_height.load(Ordering::Acquire) as u32).write(writer)?;
3173                 self.last_block_hash.lock().unwrap().write(writer)?;
3174
3175                 let channel_state = self.channel_state.lock().unwrap();
3176                 let mut unfunded_channels = 0;
3177                 for (_, channel) in channel_state.by_id.iter() {
3178                         if !channel.is_funding_initiated() {
3179                                 unfunded_channels += 1;
3180                         }
3181                 }
3182                 ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
3183                 for (_, channel) in channel_state.by_id.iter() {
3184                         if channel.is_funding_initiated() {
3185                                 channel.write(writer)?;
3186                         }
3187                 }
3188
3189                 (channel_state.forward_htlcs.len() as u64).write(writer)?;
3190                 for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
3191                         short_channel_id.write(writer)?;
3192                         (pending_forwards.len() as u64).write(writer)?;
3193                         for forward in pending_forwards {
3194                                 forward.write(writer)?;
3195                         }
3196                 }
3197
3198                 (channel_state.claimable_htlcs.len() as u64).write(writer)?;
3199                 for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
3200                         payment_hash.write(writer)?;
3201                         (previous_hops.len() as u64).write(writer)?;
3202                         for previous_hop in previous_hops {
3203                                 previous_hop.write(writer)?;
3204                         }
3205                 }
3206
3207                 Ok(())
3208         }
3209 }
3210
3211 /// Arguments for the creation of a ChannelManager that are not deserialized.
3212 ///
3213 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
3214 /// is:
3215 /// 1) Deserialize all stored ChannelMonitors.
3216 /// 2) Deserialize the ChannelManager by filling in this struct and calling <(Sha256dHash,
3217 ///    ChannelManager)>::read(reader, args).
3218 ///    This may result in closing some Channels if the ChannelMonitor is newer than the stored
3219 ///    ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
3220 /// 3) Register all relevant ChannelMonitor outpoints with your chain watch mechanism using
3221 ///    ChannelMonitor::get_monitored_outpoints and ChannelMonitor::get_funding_txo().
3222 /// 4) Reconnect blocks on your ChannelMonitors.
3223 /// 5) Move the ChannelMonitors into your local ManyChannelMonitor.
3224 /// 6) Disconnect/connect blocks on the ChannelManager.
3225 /// 7) Register the new ChannelManager with your ChainWatchInterface (this does not happen
3226 ///    automatically as it does in ChannelManager::new()).
3227 pub struct ChannelManagerReadArgs<'a> {
3228         /// The keys provider which will give us relevant keys. Some keys will be loaded during
3229         /// deserialization.
3230         pub keys_manager: Arc<KeysInterface>,
3231
3232         /// The fee_estimator for use in the ChannelManager in the future.
3233         ///
3234         /// No calls to the FeeEstimator will be made during deserialization.
3235         pub fee_estimator: Arc<FeeEstimator>,
3236         /// The ManyChannelMonitor for use in the ChannelManager in the future.
3237         ///
3238         /// No calls to the ManyChannelMonitor will be made during deserialization. It is assumed that
3239         /// you have deserialized ChannelMonitors separately and will add them to your
3240         /// ManyChannelMonitor after deserializing this ChannelManager.
3241         pub monitor: Arc<ManyChannelMonitor>,
3242         /// The ChainWatchInterface for use in the ChannelManager in the future.
3243         ///
3244         /// No calls to the ChainWatchInterface will be made during deserialization.
3245         pub chain_monitor: Arc<ChainWatchInterface>,
3246         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
3247         /// used to broadcast the latest local commitment transactions of channels which must be
3248         /// force-closed during deserialization.
3249         pub tx_broadcaster: Arc<BroadcasterInterface>,
3250         /// The Logger for use in the ChannelManager and which may be used to log information during
3251         /// deserialization.
3252         pub logger: Arc<Logger>,
3253         /// Default settings used for new channels. Any existing channels will continue to use the
3254         /// runtime settings which were stored when the ChannelManager was serialized.
3255         pub default_config: UserConfig,
3256
3257         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
3258         /// value.get_funding_txo() should be the key).
3259         ///
3260         /// If a monitor is inconsistent with the channel state during deserialization the channel will
3261         /// be force-closed using the data in the channelmonitor and the Channel will be dropped. This
3262         /// is true for missing channels as well. If there is a monitor missing for which we find
3263         /// channel data Err(DecodeError::InvalidValue) will be returned.
3264         ///
3265         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
3266         /// this struct.
3267         pub channel_monitors: &'a HashMap<OutPoint, &'a ChannelMonitor>,
3268 }
3269
3270 impl<'a, R : ::std::io::Read> ReadableArgs<R, ChannelManagerReadArgs<'a>> for (Sha256dHash, ChannelManager) {
3271         fn read(reader: &mut R, args: ChannelManagerReadArgs<'a>) -> Result<Self, DecodeError> {
3272                 let _ver: u8 = Readable::read(reader)?;
3273                 let min_ver: u8 = Readable::read(reader)?;
3274                 if min_ver > SERIALIZATION_VERSION {
3275                         return Err(DecodeError::UnknownVersion);
3276                 }
3277
3278                 let genesis_hash: Sha256dHash = Readable::read(reader)?;
3279                 let latest_block_height: u32 = Readable::read(reader)?;
3280                 let last_block_hash: Sha256dHash = Readable::read(reader)?;
3281
3282                 let mut closed_channels = Vec::new();
3283
3284                 let channel_count: u64 = Readable::read(reader)?;
3285                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
3286                 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3287                 let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3288                 for _ in 0..channel_count {
3289                         let mut channel: Channel = ReadableArgs::read(reader, args.logger.clone())?;
3290                         if channel.last_block_connected != last_block_hash {
3291                                 return Err(DecodeError::InvalidValue);
3292                         }
3293
3294                         let funding_txo = channel.channel_monitor().get_funding_txo().ok_or(DecodeError::InvalidValue)?;
3295                         funding_txo_set.insert(funding_txo.clone());
3296                         if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
3297                                 if channel.get_cur_local_commitment_transaction_number() != monitor.get_cur_local_commitment_number() ||
3298                                                 channel.get_revoked_remote_commitment_transaction_number() != monitor.get_min_seen_secret() ||
3299                                                 channel.get_cur_remote_commitment_transaction_number() != monitor.get_cur_remote_commitment_number() {
3300                                         let mut force_close_res = channel.force_shutdown();
3301                                         force_close_res.0 = monitor.get_latest_local_commitment_txn();
3302                                         closed_channels.push(force_close_res);
3303                                 } else {
3304                                         if let Some(short_channel_id) = channel.get_short_channel_id() {
3305                                                 short_to_id.insert(short_channel_id, channel.channel_id());
3306                                         }
3307                                         by_id.insert(channel.channel_id(), channel);
3308                                 }
3309                         } else {
3310                                 return Err(DecodeError::InvalidValue);
3311                         }
3312                 }
3313
3314                 for (ref funding_txo, ref monitor) in args.channel_monitors.iter() {
3315                         if !funding_txo_set.contains(funding_txo) {
3316                                 closed_channels.push((monitor.get_latest_local_commitment_txn(), Vec::new()));
3317                         }
3318                 }
3319
3320                 let forward_htlcs_count: u64 = Readable::read(reader)?;
3321                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
3322                 for _ in 0..forward_htlcs_count {
3323                         let short_channel_id = Readable::read(reader)?;
3324                         let pending_forwards_count: u64 = Readable::read(reader)?;
3325                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, 128));
3326                         for _ in 0..pending_forwards_count {
3327                                 pending_forwards.push(Readable::read(reader)?);
3328                         }
3329                         forward_htlcs.insert(short_channel_id, pending_forwards);
3330                 }
3331
3332                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
3333                 let mut claimable_htlcs = HashMap::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
3334                 for _ in 0..claimable_htlcs_count {
3335                         let payment_hash = Readable::read(reader)?;
3336                         let previous_hops_len: u64 = Readable::read(reader)?;
3337                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, 2));
3338                         for _ in 0..previous_hops_len {
3339                                 previous_hops.push(Readable::read(reader)?);
3340                         }
3341                         claimable_htlcs.insert(payment_hash, previous_hops);
3342                 }
3343
3344                 let channel_manager = ChannelManager {
3345                         genesis_hash,
3346                         fee_estimator: args.fee_estimator,
3347                         monitor: args.monitor,
3348                         chain_monitor: args.chain_monitor,
3349                         tx_broadcaster: args.tx_broadcaster,
3350
3351                         latest_block_height: AtomicUsize::new(latest_block_height as usize),
3352                         last_block_hash: Mutex::new(last_block_hash),
3353                         secp_ctx: Secp256k1::new(),
3354
3355                         channel_state: Mutex::new(ChannelHolder {
3356                                 by_id,
3357                                 short_to_id,
3358                                 next_forward: Instant::now(),
3359                                 forward_htlcs,
3360                                 claimable_htlcs,
3361                                 pending_msg_events: Vec::new(),
3362                         }),
3363                         our_network_key: args.keys_manager.get_node_secret(),
3364
3365                         pending_events: Mutex::new(Vec::new()),
3366                         total_consistency_lock: RwLock::new(()),
3367                         keys_manager: args.keys_manager,
3368                         logger: args.logger,
3369                         default_configuration: args.default_config,
3370                 };
3371
3372                 for close_res in closed_channels.drain(..) {
3373                         channel_manager.finish_force_close_channel(close_res);
3374                         //TODO: Broadcast channel update for closed channels, but only after we've made a
3375                         //connection or two.
3376                 }
3377
3378                 Ok((last_block_hash.clone(), channel_manager))
3379         }
3380 }
3381
3382 #[cfg(test)]
3383 mod tests {
3384         use chain::chaininterface;
3385         use chain::transaction::OutPoint;
3386         use chain::chaininterface::{ChainListener, ChainWatchInterface};
3387         use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor};
3388         use chain::keysinterface;
3389         use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
3390         use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,OnionKeys,PaymentFailReason,RAACommitmentOrder, PaymentPreimage, PaymentHash};
3391         use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, ManyChannelMonitor};
3392         use ln::channel::{ACCEPTED_HTLC_SCRIPT_WEIGHT, OFFERED_HTLC_SCRIPT_WEIGHT};
3393         use ln::router::{Route, RouteHop, Router};
3394         use ln::msgs;
3395         use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler};
3396         use util::test_utils;
3397         use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
3398         use util::errors::APIError;
3399         use util::logger::Logger;
3400         use util::ser::{Writeable, Writer, ReadableArgs};
3401         use util::config::UserConfig;
3402
3403         use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
3404         use bitcoin::util::bip143;
3405         use bitcoin::util::address::Address;
3406         use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
3407         use bitcoin::blockdata::block::{Block, BlockHeader};
3408         use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType};
3409         use bitcoin::blockdata::script::{Builder, Script};
3410         use bitcoin::blockdata::opcodes;
3411         use bitcoin::blockdata::constants::genesis_block;
3412         use bitcoin::network::constants::Network;
3413
3414         use hex;
3415
3416         use secp256k1::{Secp256k1, Message};
3417         use secp256k1::key::{PublicKey,SecretKey};
3418
3419         use crypto::sha2::Sha256;
3420         use crypto::digest::Digest;
3421
3422         use rand::{thread_rng,Rng};
3423
3424         use std::cell::RefCell;
3425         use std::collections::{BTreeSet, HashMap, HashSet};
3426         use std::default::Default;
3427         use std::rc::Rc;
3428         use std::sync::{Arc, Mutex};
3429         use std::sync::atomic::Ordering;
3430         use std::time::Instant;
3431         use std::mem;
3432
3433         fn build_test_onion_keys() -> Vec<OnionKeys> {
3434                 // Keys from BOLT 4, used in both test vector tests
3435                 let secp_ctx = Secp256k1::new();
3436
3437                 let route = Route {
3438                         hops: vec!(
3439                                         RouteHop {
3440                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
3441                                                 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
3442                                         },
3443                                         RouteHop {
3444                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
3445                                                 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
3446                                         },
3447                                         RouteHop {
3448                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
3449                                                 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
3450                                         },
3451                                         RouteHop {
3452                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..]).unwrap(),
3453                                                 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
3454                                         },
3455                                         RouteHop {
3456                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145").unwrap()[..]).unwrap(),
3457                                                 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
3458                                         },
3459                         ),
3460                 };
3461
3462                 let session_priv = SecretKey::from_slice(&secp_ctx, &hex::decode("4141414141414141414141414141414141414141414141414141414141414141").unwrap()[..]).unwrap();
3463
3464                 let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
3465                 assert_eq!(onion_keys.len(), route.hops.len());
3466                 onion_keys
3467         }
3468
3469         #[test]
3470         fn onion_vectors() {
3471                 // Packet creation test vectors from BOLT 4
3472                 let onion_keys = build_test_onion_keys();
3473
3474                 assert_eq!(onion_keys[0].shared_secret[..], hex::decode("53eb63ea8a3fec3b3cd433b85cd62a4b145e1dda09391b348c4e1cd36a03ea66").unwrap()[..]);
3475                 assert_eq!(onion_keys[0].blinding_factor[..], hex::decode("2ec2e5da605776054187180343287683aa6a51b4b1c04d6dd49c45d8cffb3c36").unwrap()[..]);
3476                 assert_eq!(onion_keys[0].ephemeral_pubkey.serialize()[..], hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]);
3477                 assert_eq!(onion_keys[0].rho, hex::decode("ce496ec94def95aadd4bec15cdb41a740c9f2b62347c4917325fcc6fb0453986").unwrap()[..]);
3478                 assert_eq!(onion_keys[0].mu, hex::decode("b57061dc6d0a2b9f261ac410c8b26d64ac5506cbba30267a649c28c179400eba").unwrap()[..]);
3479
3480                 assert_eq!(onion_keys[1].shared_secret[..], hex::decode("a6519e98832a0b179f62123b3567c106db99ee37bef036e783263602f3488fae").unwrap()[..]);
3481                 assert_eq!(onion_keys[1].blinding_factor[..], hex::decode("bf66c28bc22e598cfd574a1931a2bafbca09163df2261e6d0056b2610dab938f").unwrap()[..]);
3482                 assert_eq!(onion_keys[1].ephemeral_pubkey.serialize()[..], hex::decode("028f9438bfbf7feac2e108d677e3a82da596be706cc1cf342b75c7b7e22bf4e6e2").unwrap()[..]);
3483                 assert_eq!(onion_keys[1].rho, hex::decode("450ffcabc6449094918ebe13d4f03e433d20a3d28a768203337bc40b6e4b2c59").unwrap()[..]);
3484                 assert_eq!(onion_keys[1].mu, hex::decode("05ed2b4a3fb023c2ff5dd6ed4b9b6ea7383f5cfe9d59c11d121ec2c81ca2eea9").unwrap()[..]);
3485
3486                 assert_eq!(onion_keys[2].shared_secret[..], hex::decode("3a6b412548762f0dbccce5c7ae7bb8147d1caf9b5471c34120b30bc9c04891cc").unwrap()[..]);
3487                 assert_eq!(onion_keys[2].blinding_factor[..], hex::decode("a1f2dadd184eb1627049673f18c6325814384facdee5bfd935d9cb031a1698a5").unwrap()[..]);
3488                 assert_eq!(onion_keys[2].ephemeral_pubkey.serialize()[..], hex::decode("03bfd8225241ea71cd0843db7709f4c222f62ff2d4516fd38b39914ab6b83e0da0").unwrap()[..]);
3489                 assert_eq!(onion_keys[2].rho, hex::decode("11bf5c4f960239cb37833936aa3d02cea82c0f39fd35f566109c41f9eac8deea").unwrap()[..]);
3490                 assert_eq!(onion_keys[2].mu, hex::decode("caafe2820fa00eb2eeb78695ae452eba38f5a53ed6d53518c5c6edf76f3f5b78").unwrap()[..]);
3491
3492                 assert_eq!(onion_keys[3].shared_secret[..], hex::decode("21e13c2d7cfe7e18836df50872466117a295783ab8aab0e7ecc8c725503ad02d").unwrap()[..]);
3493                 assert_eq!(onion_keys[3].blinding_factor[..], hex::decode("7cfe0b699f35525029ae0fa437c69d0f20f7ed4e3916133f9cacbb13c82ff262").unwrap()[..]);
3494                 assert_eq!(onion_keys[3].ephemeral_pubkey.serialize()[..], hex::decode("031dde6926381289671300239ea8e57ffaf9bebd05b9a5b95beaf07af05cd43595").unwrap()[..]);
3495                 assert_eq!(onion_keys[3].rho, hex::decode("cbe784ab745c13ff5cffc2fbe3e84424aa0fd669b8ead4ee562901a4a4e89e9e").unwrap()[..]);
3496                 assert_eq!(onion_keys[3].mu, hex::decode("5052aa1b3d9f0655a0932e50d42f0c9ba0705142c25d225515c45f47c0036ee9").unwrap()[..]);
3497
3498                 assert_eq!(onion_keys[4].shared_secret[..], hex::decode("b5756b9b542727dbafc6765a49488b023a725d631af688fc031217e90770c328").unwrap()[..]);
3499                 assert_eq!(onion_keys[4].blinding_factor[..], hex::decode("c96e00dddaf57e7edcd4fb5954be5b65b09f17cb6d20651b4e90315be5779205").unwrap()[..]);
3500                 assert_eq!(onion_keys[4].ephemeral_pubkey.serialize()[..], hex::decode("03a214ebd875aab6ddfd77f22c5e7311d7f77f17a169e599f157bbcdae8bf071f4").unwrap()[..]);
3501                 assert_eq!(onion_keys[4].rho, hex::decode("034e18b8cc718e8af6339106e706c52d8df89e2b1f7e9142d996acf88df8799b").unwrap()[..]);
3502                 assert_eq!(onion_keys[4].mu, hex::decode("8e45e5c61c2b24cb6382444db6698727afb063adecd72aada233d4bf273d975a").unwrap()[..]);
3503
3504                 // Test vectors below are flat-out wrong: they claim to set outgoing_cltv_value to non-0 :/
3505                 let payloads = vec!(
3506                         msgs::OnionHopData {
3507                                 realm: 0,
3508                                 data: msgs::OnionRealm0HopData {
3509                                         short_channel_id: 0,
3510                                         amt_to_forward: 0,
3511                                         outgoing_cltv_value: 0,
3512                                 },
3513                                 hmac: [0; 32],
3514                         },
3515                         msgs::OnionHopData {
3516                                 realm: 0,
3517                                 data: msgs::OnionRealm0HopData {
3518                                         short_channel_id: 0x0101010101010101,
3519                                         amt_to_forward: 0x0100000001,
3520                                         outgoing_cltv_value: 0,
3521                                 },
3522                                 hmac: [0; 32],
3523                         },
3524                         msgs::OnionHopData {
3525                                 realm: 0,
3526                                 data: msgs::OnionRealm0HopData {
3527                                         short_channel_id: 0x0202020202020202,
3528                                         amt_to_forward: 0x0200000002,
3529                                         outgoing_cltv_value: 0,
3530                                 },
3531                                 hmac: [0; 32],
3532                         },
3533                         msgs::OnionHopData {
3534                                 realm: 0,
3535                                 data: msgs::OnionRealm0HopData {
3536                                         short_channel_id: 0x0303030303030303,
3537                                         amt_to_forward: 0x0300000003,
3538                                         outgoing_cltv_value: 0,
3539                                 },
3540                                 hmac: [0; 32],
3541                         },
3542                         msgs::OnionHopData {
3543                                 realm: 0,
3544                                 data: msgs::OnionRealm0HopData {
3545                                         short_channel_id: 0x0404040404040404,
3546                                         amt_to_forward: 0x0400000004,
3547                                         outgoing_cltv_value: 0,
3548                                 },
3549                                 hmac: [0; 32],
3550                         },
3551                 );
3552
3553                 let packet = ChannelManager::construct_onion_packet(payloads, onion_keys, &PaymentHash([0x42; 32]));
3554                 // Just check the final packet encoding, as it includes all the per-hop vectors in it
3555                 // anyway...
3556                 assert_eq!(packet.encode(), hex::decode("0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619e5f14350c2a76fc232b5e46d421e9615471ab9e0bc887beff8c95fdb878f7b3a716a996c7845c93d90e4ecbb9bde4ece2f69425c99e4bc820e44485455f135edc0d10f7d61ab590531cf08000179a333a347f8b4072f216400406bdf3bf038659793d4a1fd7b246979e3150a0a4cb052c9ec69acf0f48c3d39cd55675fe717cb7d80ce721caad69320c3a469a202f1e468c67eaf7a7cd8226d0fd32f7b48084dca885d56047694762b67021713ca673929c163ec36e04e40ca8e1c6d17569419d3039d9a1ec866abe044a9ad635778b961fc0776dc832b3a451bd5d35072d2269cf9b040f6b7a7dad84fb114ed413b1426cb96ceaf83825665ed5a1d002c1687f92465b49ed4c7f0218ff8c6c7dd7221d589c65b3b9aaa71a41484b122846c7c7b57e02e679ea8469b70e14fe4f70fee4d87b910cf144be6fe48eef24da475c0b0bcc6565ae82cd3f4e3b24c76eaa5616c6111343306ab35c1fe5ca4a77c0e314ed7dba39d6f1e0de791719c241a939cc493bea2bae1c1e932679ea94d29084278513c77b899cc98059d06a27d171b0dbdf6bee13ddc4fc17a0c4d2827d488436b57baa167544138ca2e64a11b43ac8a06cd0c2fba2d4d900ed2d9205305e2d7383cc98dacb078133de5f6fb6bed2ef26ba92cea28aafc3b9948dd9ae5559e8bd6920b8cea462aa445ca6a95e0e7ba52961b181c79e73bd581821df2b10173727a810c92b83b5ba4a0403eb710d2ca10689a35bec6c3a708e9e92f7d78ff3c5d9989574b00c6736f84c199256e76e19e78f0c98a9d580b4a658c84fc8f2096c2fbea8f5f8c59d0fdacb3be2802ef802abbecb3aba4acaac69a0e965abd8981e9896b1f6ef9d60f7a164b371af869fd0e48073742825e9434fc54da837e120266d53302954843538ea7c6c3dbfb4ff3b2fdbe244437f2a153ccf7bdb4c92aa08102d4f3cff2ae5ef86fab4653595e6a5837fa2f3e29f27a9cde5966843fb847a4a61f1e76c281fe8bb2b0a181d096100db5a1a5ce7a910238251a43ca556712eaadea167fb4d7d75825e440f3ecd782036d7574df8bceacb397abefc5f5254d2722215c53ff54af8299aaaad642c6d72a14d27882d9bbd539e1cc7a527526ba89b8c037ad09120e98ab042d3e8652b31ae0e478516bfaf88efca9f3676ffe99d2819dcaeb7610a626695f53117665d267d3f7abebd6bbd6733f645c72c389f03855bdf1e4b8075b516569b118233a0f0971d24b83113c0b096f5216a207ca99a7cddc81c130923fe3d91e7508c9ac5f2e914ff5dccab9e558566fa14efb34ac98d878580814b94b73acbfde9072f30b881f7f0fff42d4045d1ace6322d86a97d164aa84d93a60498065cc7c20e636f5862dc81531a88c60305a2e59a985be327a6902e4bed986dbf4a0b50c217af0ea7fdf9ab37f9ea1a1aaa72f54cf40154ea9b269f1a7c09f9f43245109431a175d50e2db0132337baa0ef97eed0fcf20489da36b79a1172faccc2f7ded7c60e00694282d93359c4682135642bc81f433574aa8ef0c97b4ade7ca372c5ffc23c7eddd839bab4e0f14d6df15c9dbeab176bec8b5701cf054eb3072f6dadc98f88819042bf10c407516ee58bce33fbe3b3d86a54255e577db4598e30a135361528c101683a5fcde7e8ba53f3456254be8f45fe3a56120ae96ea3773631fcb3873aa3abd91bcff00bd38bd43697a2e789e00da6077482e7b1b1a677b5afae4c54e6cbdf7377b694eb7d7a5b913476a5be923322d3de06060fd5e819635232a2cf4f0731da13b8546d1d6d4f8d75b9fce6c2341a71b0ea6f780df54bfdb0dd5cd9855179f602f9172307c7268724c3618e6817abd793adc214a0dc0bc616816632f27ea336fb56dfd").unwrap());
3557         }
3558
3559         #[test]
3560         fn test_failure_packet_onion() {
3561                 // Returning Errors test vectors from BOLT 4
3562
3563                 let onion_keys = build_test_onion_keys();
3564                 let onion_error = ChannelManager::build_failure_packet(&onion_keys[4].shared_secret[..], 0x2002, &[0; 0]);
3565                 assert_eq!(onion_error.encode(), hex::decode("4c2fc8bc08510334b6833ad9c3e79cd1b52ae59dfe5c2a4b23ead50f09f7ee0b0002200200fe0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap());
3566
3567                 let onion_packet_1 = ChannelManager::encrypt_failure_packet(&onion_keys[4].shared_secret[..], &onion_error.encode()[..]);
3568                 assert_eq!(onion_packet_1.data, hex::decode("a5e6bd0c74cb347f10cce367f949098f2457d14c046fd8a22cb96efb30b0fdcda8cb9168b50f2fd45edd73c1b0c8b33002df376801ff58aaa94000bf8a86f92620f343baef38a580102395ae3abf9128d1047a0736ff9b83d456740ebbb4aeb3aa9737f18fb4afb4aa074fb26c4d702f42968888550a3bded8c05247e045b866baef0499f079fdaeef6538f31d44deafffdfd3afa2fb4ca9082b8f1c465371a9894dd8c243fb4847e004f5256b3e90e2edde4c9fb3082ddfe4d1e734cacd96ef0706bf63c9984e22dc98851bcccd1c3494351feb458c9c6af41c0044bea3c47552b1d992ae542b17a2d0bba1a096c78d169034ecb55b6e3a7263c26017f033031228833c1daefc0dedb8cf7c3e37c9c37ebfe42f3225c326e8bcfd338804c145b16e34e4").unwrap());
3569
3570                 let onion_packet_2 = ChannelManager::encrypt_failure_packet(&onion_keys[3].shared_secret[..], &onion_packet_1.data[..]);
3571                 assert_eq!(onion_packet_2.data, hex::decode("c49a1ce81680f78f5f2000cda36268de34a3f0a0662f55b4e837c83a8773c22aa081bab1616a0011585323930fa5b9fae0c85770a2279ff59ec427ad1bbff9001c0cd1497004bd2a0f68b50704cf6d6a4bf3c8b6a0833399a24b3456961ba00736785112594f65b6b2d44d9f5ea4e49b5e1ec2af978cbe31c67114440ac51a62081df0ed46d4a3df295da0b0fe25c0115019f03f15ec86fabb4c852f83449e812f141a9395b3f70b766ebbd4ec2fae2b6955bd8f32684c15abfe8fd3a6261e52650e8807a92158d9f1463261a925e4bfba44bd20b166d532f0017185c3a6ac7957adefe45559e3072c8dc35abeba835a8cb01a71a15c736911126f27d46a36168ca5ef7dccd4e2886212602b181463e0dd30185c96348f9743a02aca8ec27c0b90dca270").unwrap());
3572
3573                 let onion_packet_3 = ChannelManager::encrypt_failure_packet(&onion_keys[2].shared_secret[..], &onion_packet_2.data[..]);
3574                 assert_eq!(onion_packet_3.data, hex::decode("a5d3e8634cfe78b2307d87c6d90be6fe7855b4f2cc9b1dfb19e92e4b79103f61ff9ac25f412ddfb7466e74f81b3e545563cdd8f5524dae873de61d7bdfccd496af2584930d2b566b4f8d3881f8c043df92224f38cf094cfc09d92655989531524593ec6d6caec1863bdfaa79229b5020acc034cd6deeea1021c50586947b9b8e6faa83b81fbfa6133c0af5d6b07c017f7158fa94f0d206baf12dda6b68f785b773b360fd0497e16cc402d779c8d48d0fa6315536ef0660f3f4e1865f5b38ea49c7da4fd959de4e83ff3ab686f059a45c65ba2af4a6a79166aa0f496bf04d06987b6d2ea205bdb0d347718b9aeff5b61dfff344993a275b79717cd815b6ad4c0beb568c4ac9c36ff1c315ec1119a1993c4b61e6eaa0375e0aaf738ac691abd3263bf937e3").unwrap());
3575
3576                 let onion_packet_4 = ChannelManager::encrypt_failure_packet(&onion_keys[1].shared_secret[..], &onion_packet_3.data[..]);
3577                 assert_eq!(onion_packet_4.data, hex::decode("aac3200c4968f56b21f53e5e374e3a2383ad2b1b6501bbcc45abc31e59b26881b7dfadbb56ec8dae8857add94e6702fb4c3a4de22e2e669e1ed926b04447fc73034bb730f4932acd62727b75348a648a1128744657ca6a4e713b9b646c3ca66cac02cdab44dd3439890ef3aaf61708714f7375349b8da541b2548d452d84de7084bb95b3ac2345201d624d31f4d52078aa0fa05a88b4e20202bd2b86ac5b52919ea305a8949de95e935eed0319cf3cf19ebea61d76ba92532497fcdc9411d06bcd4275094d0a4a3c5d3a945e43305a5a9256e333e1f64dbca5fcd4e03a39b9012d197506e06f29339dfee3331995b21615337ae060233d39befea925cc262873e0530408e6990f1cbd233a150ef7b004ff6166c70c68d9f8c853c1abca640b8660db2921").unwrap());
3578
3579                 let onion_packet_5 = ChannelManager::encrypt_failure_packet(&onion_keys[0].shared_secret[..], &onion_packet_4.data[..]);
3580                 assert_eq!(onion_packet_5.data, hex::decode("9c5add3963fc7f6ed7f148623c84134b5647e1306419dbe2174e523fa9e2fbed3a06a19f899145610741c83ad40b7712aefaddec8c6baf7325d92ea4ca4d1df8bce517f7e54554608bf2bd8071a4f52a7a2f7ffbb1413edad81eeea5785aa9d990f2865dc23b4bc3c301a94eec4eabebca66be5cf638f693ec256aec514620cc28ee4a94bd9565bc4d4962b9d3641d4278fb319ed2b84de5b665f307a2db0f7fbb757366067d88c50f7e829138fde4f78d39b5b5802f1b92a8a820865af5cc79f9f30bc3f461c66af95d13e5e1f0381c184572a91dee1c849048a647a1158cf884064deddbf1b0b88dfe2f791428d0ba0f6fb2f04e14081f69165ae66d9297c118f0907705c9c4954a199bae0bb96fad763d690e7daa6cfda59ba7f2c8d11448b604d12d").unwrap());
3581         }
3582
3583         fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
3584                 assert!(chain.does_match_tx(tx));
3585                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3586                 chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
3587                 for i in 2..100 {
3588                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3589                         chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
3590                 }
3591         }
3592
3593         struct Node {
3594                 chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
3595                 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
3596                 chan_monitor: Arc<test_utils::TestChannelMonitor>,
3597                 node: Arc<ChannelManager>,
3598                 router: Router,
3599                 node_seed: [u8; 32],
3600                 network_payment_count: Rc<RefCell<u8>>,
3601                 network_chan_count: Rc<RefCell<u32>>,
3602         }
3603         impl Drop for Node {
3604                 fn drop(&mut self) {
3605                         if !::std::thread::panicking() {
3606                                 // Check that we processed all pending events
3607                                 assert_eq!(self.node.get_and_clear_pending_msg_events().len(), 0);
3608                                 assert_eq!(self.node.get_and_clear_pending_events().len(), 0);
3609                                 assert_eq!(self.chan_monitor.added_monitors.lock().unwrap().len(), 0);
3610                         }
3611                 }
3612         }
3613
3614         fn create_chan_between_nodes(node_a: &Node, node_b: &Node) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3615                 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001)
3616         }
3617
3618         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) {
3619                 let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat);
3620                 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
3621                 (announcement, as_update, bs_update, channel_id, tx)
3622         }
3623
3624         macro_rules! get_revoke_commit_msgs {
3625                 ($node: expr, $node_id: expr) => {
3626                         {
3627                                 let events = $node.node.get_and_clear_pending_msg_events();
3628                                 assert_eq!(events.len(), 2);
3629                                 (match events[0] {
3630                                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3631                                                 assert_eq!(*node_id, $node_id);
3632                                                 (*msg).clone()
3633                                         },
3634                                         _ => panic!("Unexpected event"),
3635                                 }, match events[1] {
3636                                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3637                                                 assert_eq!(*node_id, $node_id);
3638                                                 assert!(updates.update_add_htlcs.is_empty());
3639                                                 assert!(updates.update_fulfill_htlcs.is_empty());
3640                                                 assert!(updates.update_fail_htlcs.is_empty());
3641                                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
3642                                                 assert!(updates.update_fee.is_none());
3643                                                 updates.commitment_signed.clone()
3644                                         },
3645                                         _ => panic!("Unexpected event"),
3646                                 })
3647                         }
3648                 }
3649         }
3650
3651         macro_rules! get_event_msg {
3652                 ($node: expr, $event_type: path, $node_id: expr) => {
3653                         {
3654                                 let events = $node.node.get_and_clear_pending_msg_events();
3655                                 assert_eq!(events.len(), 1);
3656                                 match events[0] {
3657                                         $event_type { ref node_id, ref msg } => {
3658                                                 assert_eq!(*node_id, $node_id);
3659                                                 (*msg).clone()
3660                                         },
3661                                         _ => panic!("Unexpected event"),
3662                                 }
3663                         }
3664                 }
3665         }
3666
3667         macro_rules! get_htlc_update_msgs {
3668                 ($node: expr, $node_id: expr) => {
3669                         {
3670                                 let events = $node.node.get_and_clear_pending_msg_events();
3671                                 assert_eq!(events.len(), 1);
3672                                 match events[0] {
3673                                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3674                                                 assert_eq!(*node_id, $node_id);
3675                                                 (*updates).clone()
3676                                         },
3677                                         _ => panic!("Unexpected event"),
3678                                 }
3679                         }
3680                 }
3681         }
3682
3683         macro_rules! get_feerate {
3684                 ($node: expr, $channel_id: expr) => {
3685                         {
3686                                 let chan_lock = $node.node.channel_state.lock().unwrap();
3687                                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
3688                                 chan.get_feerate()
3689                         }
3690                 }
3691         }
3692
3693
3694         fn create_chan_between_nodes_with_value_init(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> Transaction {
3695                 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
3696                 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();
3697                 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();
3698
3699                 let chan_id = *node_a.network_chan_count.borrow();
3700                 let tx;
3701                 let funding_output;
3702
3703                 let events_2 = node_a.node.get_and_clear_pending_events();
3704                 assert_eq!(events_2.len(), 1);
3705                 match events_2[0] {
3706                         Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
3707                                 assert_eq!(*channel_value_satoshis, channel_value);
3708                                 assert_eq!(user_channel_id, 42);
3709
3710                                 tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
3711                                         value: *channel_value_satoshis, script_pubkey: output_script.clone(),
3712                                 }]};
3713                                 funding_output = OutPoint::new(tx.txid(), 0);
3714
3715                                 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
3716                                 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3717                                 assert_eq!(added_monitors.len(), 1);
3718                                 assert_eq!(added_monitors[0].0, funding_output);
3719                                 added_monitors.clear();
3720                         },
3721                         _ => panic!("Unexpected event"),
3722                 }
3723
3724                 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();
3725                 {
3726                         let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
3727                         assert_eq!(added_monitors.len(), 1);
3728                         assert_eq!(added_monitors[0].0, funding_output);
3729                         added_monitors.clear();
3730                 }
3731
3732                 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();
3733                 {
3734                         let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3735                         assert_eq!(added_monitors.len(), 1);
3736                         assert_eq!(added_monitors[0].0, funding_output);
3737                         added_monitors.clear();
3738                 }
3739
3740                 let events_4 = node_a.node.get_and_clear_pending_events();
3741                 assert_eq!(events_4.len(), 1);
3742                 match events_4[0] {
3743                         Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
3744                                 assert_eq!(user_channel_id, 42);
3745                                 assert_eq!(*funding_txo, funding_output);
3746                         },
3747                         _ => panic!("Unexpected event"),
3748                 };
3749
3750                 tx
3751         }
3752
3753         fn create_chan_between_nodes_with_value_confirm(node_a: &Node, node_b: &Node, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
3754                 confirm_transaction(&node_b.chain_monitor, &tx, tx.version);
3755                 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();
3756
3757                 let channel_id;
3758
3759                 confirm_transaction(&node_a.chain_monitor, &tx, tx.version);
3760                 let events_6 = node_a.node.get_and_clear_pending_msg_events();
3761                 assert_eq!(events_6.len(), 2);
3762                 ((match events_6[0] {
3763                         MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3764                                 channel_id = msg.channel_id.clone();
3765                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
3766                                 msg.clone()
3767                         },
3768                         _ => panic!("Unexpected event"),
3769                 }, match events_6[1] {
3770                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3771                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
3772                                 msg.clone()
3773                         },
3774                         _ => panic!("Unexpected event"),
3775                 }), channel_id)
3776         }
3777
3778         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) {
3779                 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat);
3780                 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
3781                 (msgs, chan_id, tx)
3782         }
3783
3784         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) {
3785                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0).unwrap();
3786                 let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
3787                 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1).unwrap();
3788
3789                 let events_7 = node_b.node.get_and_clear_pending_msg_events();
3790                 assert_eq!(events_7.len(), 1);
3791                 let (announcement, bs_update) = match events_7[0] {
3792                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3793                                 (msg, update_msg)
3794                         },
3795                         _ => panic!("Unexpected event"),
3796                 };
3797
3798                 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs).unwrap();
3799                 let events_8 = node_a.node.get_and_clear_pending_msg_events();
3800                 assert_eq!(events_8.len(), 1);
3801                 let as_update = match events_8[0] {
3802                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3803                                 assert!(*announcement == *msg);
3804                                 update_msg
3805                         },
3806                         _ => panic!("Unexpected event"),
3807                 };
3808
3809                 *node_a.network_chan_count.borrow_mut() += 1;
3810
3811                 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
3812         }
3813
3814         fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3815                 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001)
3816         }
3817
3818         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) {
3819                 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat);
3820                 for node in nodes {
3821                         assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
3822                         node.router.handle_channel_update(&chan_announcement.1).unwrap();
3823                         node.router.handle_channel_update(&chan_announcement.2).unwrap();
3824                 }
3825                 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
3826         }
3827
3828         macro_rules! check_spends {
3829                 ($tx: expr, $spends_tx: expr) => {
3830                         {
3831                                 let mut funding_tx_map = HashMap::new();
3832                                 let spends_tx = $spends_tx;
3833                                 funding_tx_map.insert(spends_tx.txid(), spends_tx);
3834                                 $tx.verify(&funding_tx_map).unwrap();
3835                         }
3836                 }
3837         }
3838
3839         macro_rules! get_closing_signed_broadcast {
3840                 ($node: expr, $dest_pubkey: expr) => {
3841                         {
3842                                 let events = $node.get_and_clear_pending_msg_events();
3843                                 assert!(events.len() == 1 || events.len() == 2);
3844                                 (match events[events.len() - 1] {
3845                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
3846                                                 assert_eq!(msg.contents.flags & 2, 2);
3847                                                 msg.clone()
3848                                         },
3849                                         _ => panic!("Unexpected event"),
3850                                 }, if events.len() == 2 {
3851                                         match events[0] {
3852                                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3853                                                         assert_eq!(*node_id, $dest_pubkey);
3854                                                         Some(msg.clone())
3855                                                 },
3856                                                 _ => panic!("Unexpected event"),
3857                                         }
3858                                 } else { None })
3859                         }
3860                 }
3861         }
3862
3863         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) {
3864                 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) };
3865                 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
3866                 let (tx_a, tx_b);
3867
3868                 node_a.close_channel(channel_id).unwrap();
3869                 node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id())).unwrap();
3870
3871                 let events_1 = node_b.get_and_clear_pending_msg_events();
3872                 assert!(events_1.len() >= 1);
3873                 let shutdown_b = match events_1[0] {
3874                         MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
3875                                 assert_eq!(node_id, &node_a.get_our_node_id());
3876                                 msg.clone()
3877                         },
3878                         _ => panic!("Unexpected event"),
3879                 };
3880
3881                 let closing_signed_b = if !close_inbound_first {
3882                         assert_eq!(events_1.len(), 1);
3883                         None
3884                 } else {
3885                         Some(match events_1[1] {
3886                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3887                                         assert_eq!(node_id, &node_a.get_our_node_id());
3888                                         msg.clone()
3889                                 },
3890                                 _ => panic!("Unexpected event"),
3891                         })
3892                 };
3893
3894                 node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b).unwrap();
3895                 let (as_update, bs_update) = if close_inbound_first {
3896                         assert!(node_a.get_and_clear_pending_msg_events().is_empty());
3897                         node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3898                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3899                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3900                         let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3901
3902                         node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
3903                         let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3904                         assert!(none_b.is_none());
3905                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3906                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3907                         (as_update, bs_update)
3908                 } else {
3909                         let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
3910
3911                         node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a).unwrap();
3912                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3913                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3914                         let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3915
3916                         node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3917                         let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3918                         assert!(none_a.is_none());
3919                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3920                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3921                         (as_update, bs_update)
3922                 };
3923                 assert_eq!(tx_a, tx_b);
3924                 check_spends!(tx_a, funding_tx);
3925
3926                 (as_update, bs_update, tx_a)
3927         }
3928
3929         struct SendEvent {
3930                 node_id: PublicKey,
3931                 msgs: Vec<msgs::UpdateAddHTLC>,
3932                 commitment_msg: msgs::CommitmentSigned,
3933         }
3934         impl SendEvent {
3935                 fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
3936                         assert!(updates.update_fulfill_htlcs.is_empty());
3937                         assert!(updates.update_fail_htlcs.is_empty());
3938                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3939                         assert!(updates.update_fee.is_none());
3940                         SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
3941                 }
3942
3943                 fn from_event(event: MessageSendEvent) -> SendEvent {
3944                         match event {
3945                                 MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
3946                                 _ => panic!("Unexpected event type!"),
3947                         }
3948                 }
3949
3950                 fn from_node(node: &Node) -> SendEvent {
3951                         let mut events = node.node.get_and_clear_pending_msg_events();
3952                         assert_eq!(events.len(), 1);
3953                         SendEvent::from_event(events.pop().unwrap())
3954                 }
3955         }
3956
3957         macro_rules! check_added_monitors {
3958                 ($node: expr, $count: expr) => {
3959                         {
3960                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
3961                                 assert_eq!(added_monitors.len(), $count);
3962                                 added_monitors.clear();
3963                         }
3964                 }
3965         }
3966
3967         macro_rules! commitment_signed_dance {
3968                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
3969                         {
3970                                 check_added_monitors!($node_a, 0);
3971                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3972                                 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3973                                 check_added_monitors!($node_a, 1);
3974                                 commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
3975                         }
3976                 };
3977                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
3978                         {
3979                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
3980                                 check_added_monitors!($node_b, 0);
3981                                 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3982                                 $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
3983                                 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3984                                 check_added_monitors!($node_b, 1);
3985                                 $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed).unwrap();
3986                                 let (bs_revoke_and_ack, extra_msg_option) = {
3987                                         let events = $node_b.node.get_and_clear_pending_msg_events();
3988                                         assert!(events.len() <= 2);
3989                                         (match events[0] {
3990                                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3991                                                         assert_eq!(*node_id, $node_a.node.get_our_node_id());
3992                                                         (*msg).clone()
3993                                                 },
3994                                                 _ => panic!("Unexpected event"),
3995                                         }, events.get(1).map(|e| e.clone()))
3996                                 };
3997                                 check_added_monitors!($node_b, 1);
3998                                 if $fail_backwards {
3999                                         assert!($node_a.node.get_and_clear_pending_events().is_empty());
4000                                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
4001                                 }
4002                                 (extra_msg_option, bs_revoke_and_ack)
4003                         }
4004                 };
4005                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
4006                         {
4007                                 check_added_monitors!($node_a, 0);
4008                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
4009                                 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
4010                                 check_added_monitors!($node_a, 1);
4011                                 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
4012                                 assert!(extra_msg_option.is_none());
4013                                 bs_revoke_and_ack
4014                         }
4015                 };
4016                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
4017                         {
4018                                 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
4019                                 $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
4020                                 {
4021                                         let mut added_monitors = $node_a.chan_monitor.added_monitors.lock().unwrap();
4022                                         if $fail_backwards {
4023                                                 assert_eq!(added_monitors.len(), 2);
4024                                                 assert!(added_monitors[0].0 != added_monitors[1].0);
4025                                         } else {
4026                                                 assert_eq!(added_monitors.len(), 1);
4027                                         }
4028                                         added_monitors.clear();
4029                                 }
4030                                 extra_msg_option
4031                         }
4032                 };
4033                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
4034                         {
4035                                 assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
4036                         }
4037                 };
4038                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
4039                         {
4040                                 commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
4041                                 if $fail_backwards {
4042                                         let channel_state = $node_a.node.channel_state.lock().unwrap();
4043                                         assert_eq!(channel_state.pending_msg_events.len(), 1);
4044                                         if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
4045                                                 assert_ne!(*node_id, $node_b.node.get_our_node_id());
4046                                         } else { panic!("Unexpected event"); }
4047                                 } else {
4048                                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
4049                                 }
4050                         }
4051                 }
4052         }
4053
4054         macro_rules! get_payment_preimage_hash {
4055                 ($node: expr) => {
4056                         {
4057                                 let payment_preimage = PaymentPreimage([*$node.network_payment_count.borrow(); 32]);
4058                                 *$node.network_payment_count.borrow_mut() += 1;
4059                                 let mut payment_hash = PaymentHash([0; 32]);
4060                                 let mut sha = Sha256::new();
4061                                 sha.input(&payment_preimage.0[..]);
4062                                 sha.result(&mut payment_hash.0[..]);
4063                                 (payment_preimage, payment_hash)
4064                         }
4065                 }
4066         }
4067
4068         fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
4069                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4070
4071                 let mut payment_event = {
4072                         origin_node.node.send_payment(route, our_payment_hash).unwrap();
4073                         check_added_monitors!(origin_node, 1);
4074
4075                         let mut events = origin_node.node.get_and_clear_pending_msg_events();
4076                         assert_eq!(events.len(), 1);
4077                         SendEvent::from_event(events.remove(0))
4078                 };
4079                 let mut prev_node = origin_node;
4080
4081                 for (idx, &node) in expected_route.iter().enumerate() {
4082                         assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
4083
4084                         node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4085                         check_added_monitors!(node, 0);
4086                         commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
4087
4088                         let events_1 = node.node.get_and_clear_pending_events();
4089                         assert_eq!(events_1.len(), 1);
4090                         match events_1[0] {
4091                                 Event::PendingHTLCsForwardable { .. } => { },
4092                                 _ => panic!("Unexpected event"),
4093                         };
4094
4095                         node.node.channel_state.lock().unwrap().next_forward = Instant::now();
4096                         node.node.process_pending_htlc_forwards();
4097
4098                         if idx == expected_route.len() - 1 {
4099                                 let events_2 = node.node.get_and_clear_pending_events();
4100                                 assert_eq!(events_2.len(), 1);
4101                                 match events_2[0] {
4102                                         Event::PaymentReceived { ref payment_hash, amt } => {
4103                                                 assert_eq!(our_payment_hash, *payment_hash);
4104                                                 assert_eq!(amt, recv_value);
4105                                         },
4106                                         _ => panic!("Unexpected event"),
4107                                 }
4108                         } else {
4109                                 let mut events_2 = node.node.get_and_clear_pending_msg_events();
4110                                 assert_eq!(events_2.len(), 1);
4111                                 check_added_monitors!(node, 1);
4112                                 payment_event = SendEvent::from_event(events_2.remove(0));
4113                                 assert_eq!(payment_event.msgs.len(), 1);
4114                         }
4115
4116                         prev_node = node;
4117                 }
4118
4119                 (our_payment_preimage, our_payment_hash)
4120         }
4121
4122         fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: PaymentPreimage) {
4123                 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
4124                 check_added_monitors!(expected_route.last().unwrap(), 1);
4125
4126                 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
4127                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4128                 macro_rules! get_next_msgs {
4129                         ($node: expr) => {
4130                                 {
4131                                         let events = $node.node.get_and_clear_pending_msg_events();
4132                                         assert_eq!(events.len(), 1);
4133                                         match events[0] {
4134                                                 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 } } => {
4135                                                         assert!(update_add_htlcs.is_empty());
4136                                                         assert_eq!(update_fulfill_htlcs.len(), 1);
4137                                                         assert!(update_fail_htlcs.is_empty());
4138                                                         assert!(update_fail_malformed_htlcs.is_empty());
4139                                                         assert!(update_fee.is_none());
4140                                                         expected_next_node = node_id.clone();
4141                                                         Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()))
4142                                                 },
4143                                                 _ => panic!("Unexpected event"),
4144                                         }
4145                                 }
4146                         }
4147                 }
4148
4149                 macro_rules! last_update_fulfill_dance {
4150                         ($node: expr, $prev_node: expr) => {
4151                                 {
4152                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4153                                         check_added_monitors!($node, 0);
4154                                         assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4155                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4156                                 }
4157                         }
4158                 }
4159                 macro_rules! mid_update_fulfill_dance {
4160                         ($node: expr, $prev_node: expr, $new_msgs: expr) => {
4161                                 {
4162                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4163                                         check_added_monitors!($node, 1);
4164                                         let new_next_msgs = if $new_msgs {
4165                                                 get_next_msgs!($node)
4166                                         } else {
4167                                                 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4168                                                 None
4169                                         };
4170                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4171                                         next_msgs = new_next_msgs;
4172                                 }
4173                         }
4174                 }
4175
4176                 let mut prev_node = expected_route.last().unwrap();
4177                 for (idx, node) in expected_route.iter().rev().enumerate() {
4178                         assert_eq!(expected_next_node, node.node.get_our_node_id());
4179                         let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
4180                         if next_msgs.is_some() {
4181                                 mid_update_fulfill_dance!(node, prev_node, update_next_msgs);
4182                         } else if update_next_msgs {
4183                                 next_msgs = get_next_msgs!(node);
4184                         } else {
4185                                 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
4186                         }
4187                         if !skip_last && idx == expected_route.len() - 1 {
4188                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4189                         }
4190
4191                         prev_node = node;
4192                 }
4193
4194                 if !skip_last {
4195                         last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
4196                         let events = origin_node.node.get_and_clear_pending_events();
4197                         assert_eq!(events.len(), 1);
4198                         match events[0] {
4199                                 Event::PaymentSent { payment_preimage } => {
4200                                         assert_eq!(payment_preimage, our_payment_preimage);
4201                                 },
4202                                 _ => panic!("Unexpected event"),
4203                         }
4204                 }
4205         }
4206
4207         fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: PaymentPreimage) {
4208                 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage);
4209         }
4210
4211         const TEST_FINAL_CLTV: u32 = 32;
4212
4213         fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
4214                 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();
4215                 assert_eq!(route.hops.len(), expected_route.len());
4216                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4217                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
4218                 }
4219
4220                 send_along_route(origin_node, route, expected_route, recv_value)
4221         }
4222
4223         fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
4224                 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();
4225                 assert_eq!(route.hops.len(), expected_route.len());
4226                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4227                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
4228                 }
4229
4230                 let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4231
4232                 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
4233                 match err {
4234                         APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
4235                         _ => panic!("Unknown error variants"),
4236                 };
4237         }
4238
4239         fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
4240                 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
4241                 claim_payment(&origin, expected_route, our_payment_preimage);
4242         }
4243
4244         fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: PaymentHash) {
4245                 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash, PaymentFailReason::PreimageUnknown));
4246                 check_added_monitors!(expected_route.last().unwrap(), 1);
4247
4248                 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
4249                 macro_rules! update_fail_dance {
4250                         ($node: expr, $prev_node: expr, $last_node: expr) => {
4251                                 {
4252                                         $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4253                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
4254                                 }
4255                         }
4256                 }
4257
4258                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4259                 let mut prev_node = expected_route.last().unwrap();
4260                 for (idx, node) in expected_route.iter().rev().enumerate() {
4261                         assert_eq!(expected_next_node, node.node.get_our_node_id());
4262                         if next_msgs.is_some() {
4263                                 // We may be the "last node" for the purpose of the commitment dance if we're
4264                                 // skipping the last node (implying it is disconnected) and we're the
4265                                 // second-to-last node!
4266                                 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
4267                         }
4268
4269                         let events = node.node.get_and_clear_pending_msg_events();
4270                         if !skip_last || idx != expected_route.len() - 1 {
4271                                 assert_eq!(events.len(), 1);
4272                                 match events[0] {
4273                                         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 } } => {
4274                                                 assert!(update_add_htlcs.is_empty());
4275                                                 assert!(update_fulfill_htlcs.is_empty());
4276                                                 assert_eq!(update_fail_htlcs.len(), 1);
4277                                                 assert!(update_fail_malformed_htlcs.is_empty());
4278                                                 assert!(update_fee.is_none());
4279                                                 expected_next_node = node_id.clone();
4280                                                 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
4281                                         },
4282                                         _ => panic!("Unexpected event"),
4283                                 }
4284                         } else {
4285                                 assert!(events.is_empty());
4286                         }
4287                         if !skip_last && idx == expected_route.len() - 1 {
4288                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4289                         }
4290
4291                         prev_node = node;
4292                 }
4293
4294                 if !skip_last {
4295                         update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
4296
4297                         let events = origin_node.node.get_and_clear_pending_events();
4298                         assert_eq!(events.len(), 1);
4299                         match events[0] {
4300                                 Event::PaymentFailed { payment_hash, rejected_by_dest } => {
4301                                         assert_eq!(payment_hash, our_payment_hash);
4302                                         assert!(rejected_by_dest);
4303                                 },
4304                                 _ => panic!("Unexpected event"),
4305                         }
4306                 }
4307         }
4308
4309         fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: PaymentHash) {
4310                 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
4311         }
4312
4313         fn create_network(node_count: usize) -> Vec<Node> {
4314                 let mut nodes = Vec::new();
4315                 let mut rng = thread_rng();
4316                 let secp_ctx = Secp256k1::new();
4317
4318                 let chan_count = Rc::new(RefCell::new(0));
4319                 let payment_count = Rc::new(RefCell::new(0));
4320
4321                 for i in 0..node_count {
4322                         let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
4323                         let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
4324                         let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
4325                         let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
4326                         let mut seed = [0; 32];
4327                         rng.fill_bytes(&mut seed);
4328                         let keys_manager = Arc::new(keysinterface::KeysManager::new(&seed, Network::Testnet, Arc::clone(&logger)));
4329                         let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone()));
4330                         let mut config = UserConfig::new();
4331                         config.channel_options.announced_channel = true;
4332                         config.channel_limits.force_announced_channel_preference = false;
4333                         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();
4334                         let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), chain_monitor.clone(), Arc::clone(&logger));
4335                         nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router, node_seed: seed,
4336                                 network_payment_count: payment_count.clone(),
4337                                 network_chan_count: chan_count.clone(),
4338                         });
4339                 }
4340
4341                 nodes
4342         }
4343
4344         #[test]
4345         fn test_async_inbound_update_fee() {
4346                 let mut nodes = create_network(2);
4347                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4348                 let channel_id = chan.2;
4349
4350                 // balancing
4351                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4352
4353                 // A                                        B
4354                 // update_fee                            ->
4355                 // send (1) commitment_signed            -.
4356                 //                                       <- update_add_htlc/commitment_signed
4357                 // send (2) RAA (awaiting remote revoke) -.
4358                 // (1) commitment_signed is delivered    ->
4359                 //                                       .- send (3) RAA (awaiting remote revoke)
4360                 // (2) RAA is delivered                  ->
4361                 //                                       .- send (4) commitment_signed
4362                 //                                       <- (3) RAA is delivered
4363                 // send (5) commitment_signed            -.
4364                 //                                       <- (4) commitment_signed is delivered
4365                 // send (6) RAA                          -.
4366                 // (5) commitment_signed is delivered    ->
4367                 //                                       <- RAA
4368                 // (6) RAA is delivered                  ->
4369
4370                 // First nodes[0] generates an update_fee
4371                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4372                 check_added_monitors!(nodes[0], 1);
4373
4374                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4375                 assert_eq!(events_0.len(), 1);
4376                 let (update_msg, commitment_signed) = match events_0[0] { // (1)
4377                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4378                                 (update_fee.as_ref(), commitment_signed)
4379                         },
4380                         _ => panic!("Unexpected event"),
4381                 };
4382
4383                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4384
4385                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4386                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4387                 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();
4388                 check_added_monitors!(nodes[1], 1);
4389
4390                 let payment_event = {
4391                         let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4392                         assert_eq!(events_1.len(), 1);
4393                         SendEvent::from_event(events_1.remove(0))
4394                 };
4395                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4396                 assert_eq!(payment_event.msgs.len(), 1);
4397
4398                 // ...now when the messages get delivered everyone should be happy
4399                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4400                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4401                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4402                 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4403                 check_added_monitors!(nodes[0], 1);
4404
4405                 // deliver(1), generate (3):
4406                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4407                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4408                 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
4409                 check_added_monitors!(nodes[1], 1);
4410
4411                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap(); // deliver (2)
4412                 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4413                 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
4414                 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
4415                 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
4416                 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
4417                 assert!(bs_update.update_fee.is_none()); // (4)
4418                 check_added_monitors!(nodes[1], 1);
4419
4420                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap(); // deliver (3)
4421                 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4422                 assert!(as_update.update_add_htlcs.is_empty()); // (5)
4423                 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
4424                 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
4425                 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
4426                 assert!(as_update.update_fee.is_none()); // (5)
4427                 check_added_monitors!(nodes[0], 1);
4428
4429                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed).unwrap(); // deliver (4)
4430                 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4431                 // only (6) so get_event_msg's assert(len == 1) passes
4432                 check_added_monitors!(nodes[0], 1);
4433
4434                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed).unwrap(); // deliver (5)
4435                 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4436                 check_added_monitors!(nodes[1], 1);
4437
4438                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4439                 check_added_monitors!(nodes[0], 1);
4440
4441                 let events_2 = nodes[0].node.get_and_clear_pending_events();
4442                 assert_eq!(events_2.len(), 1);
4443                 match events_2[0] {
4444                         Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
4445                         _ => panic!("Unexpected event"),
4446                 }
4447
4448                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap(); // deliver (6)
4449                 check_added_monitors!(nodes[1], 1);
4450         }
4451
4452         #[test]
4453         fn test_update_fee_unordered_raa() {
4454                 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
4455                 // crash in an earlier version of the update_fee patch)
4456                 let mut nodes = create_network(2);
4457                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4458                 let channel_id = chan.2;
4459
4460                 // balancing
4461                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4462
4463                 // First nodes[0] generates an update_fee
4464                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4465                 check_added_monitors!(nodes[0], 1);
4466
4467                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4468                 assert_eq!(events_0.len(), 1);
4469                 let update_msg = match events_0[0] { // (1)
4470                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
4471                                 update_fee.as_ref()
4472                         },
4473                         _ => panic!("Unexpected event"),
4474                 };
4475
4476                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4477
4478                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4479                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4480                 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();
4481                 check_added_monitors!(nodes[1], 1);
4482
4483                 let payment_event = {
4484                         let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4485                         assert_eq!(events_1.len(), 1);
4486                         SendEvent::from_event(events_1.remove(0))
4487                 };
4488                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4489                 assert_eq!(payment_event.msgs.len(), 1);
4490
4491                 // ...now when the messages get delivered everyone should be happy
4492                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4493                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4494                 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4495                 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4496                 check_added_monitors!(nodes[0], 1);
4497
4498                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap(); // deliver (2)
4499                 check_added_monitors!(nodes[1], 1);
4500
4501                 // We can't continue, sadly, because our (1) now has a bogus signature
4502         }
4503
4504         #[test]
4505         fn test_multi_flight_update_fee() {
4506                 let nodes = create_network(2);
4507                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4508                 let channel_id = chan.2;
4509
4510                 // A                                        B
4511                 // update_fee/commitment_signed          ->
4512                 //                                       .- send (1) RAA and (2) commitment_signed
4513                 // update_fee (never committed)          ->
4514                 // (3) update_fee                        ->
4515                 // We have to manually generate the above update_fee, it is allowed by the protocol but we
4516                 // don't track which updates correspond to which revoke_and_ack responses so we're in
4517                 // AwaitingRAA mode and will not generate the update_fee yet.
4518                 //                                       <- (1) RAA delivered
4519                 // (3) is generated and send (4) CS      -.
4520                 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
4521                 // know the per_commitment_point to use for it.
4522                 //                                       <- (2) commitment_signed delivered
4523                 // revoke_and_ack                        ->
4524                 //                                          B should send no response here
4525                 // (4) commitment_signed delivered       ->
4526                 //                                       <- RAA/commitment_signed delivered
4527                 // revoke_and_ack                        ->
4528
4529                 // First nodes[0] generates an update_fee
4530                 let initial_feerate = get_feerate!(nodes[0], channel_id);
4531                 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
4532                 check_added_monitors!(nodes[0], 1);
4533
4534                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4535                 assert_eq!(events_0.len(), 1);
4536                 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
4537                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4538                                 (update_fee.as_ref().unwrap(), commitment_signed)
4539                         },
4540                         _ => panic!("Unexpected event"),
4541                 };
4542
4543                 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
4544                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1).unwrap();
4545                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1).unwrap();
4546                 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4547                 check_added_monitors!(nodes[1], 1);
4548
4549                 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
4550                 // transaction:
4551                 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
4552                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4553                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4554
4555                 // Create the (3) update_fee message that nodes[0] will generate before it does...
4556                 let mut update_msg_2 = msgs::UpdateFee {
4557                         channel_id: update_msg_1.channel_id.clone(),
4558                         feerate_per_kw: (initial_feerate + 30) as u32,
4559                 };
4560
4561                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4562
4563                 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
4564                 // Deliver (3)
4565                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4566
4567                 // Deliver (1), generating (3) and (4)
4568                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap();
4569                 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4570                 check_added_monitors!(nodes[0], 1);
4571                 assert!(as_second_update.update_add_htlcs.is_empty());
4572                 assert!(as_second_update.update_fulfill_htlcs.is_empty());
4573                 assert!(as_second_update.update_fail_htlcs.is_empty());
4574                 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
4575                 // Check that the update_fee newly generated matches what we delivered:
4576                 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
4577                 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
4578
4579                 // Deliver (2) commitment_signed
4580                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
4581                 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4582                 check_added_monitors!(nodes[0], 1);
4583                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4584
4585                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap();
4586                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4587                 check_added_monitors!(nodes[1], 1);
4588
4589                 // Delever (4)
4590                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed).unwrap();
4591                 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4592                 check_added_monitors!(nodes[1], 1);
4593
4594                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4595                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4596                 check_added_monitors!(nodes[0], 1);
4597
4598                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment).unwrap();
4599                 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4600                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4601                 check_added_monitors!(nodes[0], 1);
4602
4603                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap();
4604                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4605                 check_added_monitors!(nodes[1], 1);
4606         }
4607
4608         #[test]
4609         fn test_update_fee_vanilla() {
4610                 let nodes = create_network(2);
4611                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4612                 let channel_id = chan.2;
4613
4614                 let feerate = get_feerate!(nodes[0], channel_id);
4615                 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
4616                 check_added_monitors!(nodes[0], 1);
4617
4618                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4619                 assert_eq!(events_0.len(), 1);
4620                 let (update_msg, commitment_signed) = match events_0[0] {
4621                                 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 } } => {
4622                                 (update_fee.as_ref(), commitment_signed)
4623                         },
4624                         _ => panic!("Unexpected event"),
4625                 };
4626                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4627
4628                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4629                 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4630                 check_added_monitors!(nodes[1], 1);
4631
4632                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4633                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4634                 check_added_monitors!(nodes[0], 1);
4635
4636                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4637                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4638                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4639                 check_added_monitors!(nodes[0], 1);
4640
4641                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4642                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4643                 check_added_monitors!(nodes[1], 1);
4644         }
4645
4646         #[test]
4647         fn test_update_fee_that_funder_cannot_afford() {
4648                 let nodes = create_network(2);
4649                 let channel_value = 1888;
4650                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000);
4651                 let channel_id = chan.2;
4652
4653                 let feerate = 260;
4654                 nodes[0].node.update_fee(channel_id, feerate).unwrap();
4655                 check_added_monitors!(nodes[0], 1);
4656                 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4657
4658                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap()).unwrap();
4659
4660                 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
4661
4662                 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
4663                 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
4664                 {
4665                         let chan_lock = nodes[1].node.channel_state.lock().unwrap();
4666                         let chan = chan_lock.by_id.get(&channel_id).unwrap();
4667
4668                         //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
4669                         let num_htlcs = chan.last_local_commitment_txn[0].output.len() - 2;
4670                         let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
4671                         let mut actual_fee = chan.last_local_commitment_txn[0].output.iter().fold(0, |acc, output| acc + output.value);
4672                         actual_fee = channel_value - actual_fee;
4673                         assert_eq!(total_fee, actual_fee);
4674                 } //drop the mutex
4675
4676                 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
4677                 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
4678                 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
4679                 check_added_monitors!(nodes[0], 1);
4680
4681                 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4682
4683                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap()).unwrap();
4684
4685                 //While producing the commitment_signed response after handling a received update_fee request the
4686                 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
4687                 //Should produce and error.
4688                 let err = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed).unwrap_err();
4689
4690                 assert!(match err.err {
4691                         "Funding remote cannot afford proposed new fee" => true,
4692                         _ => false,
4693                 });
4694
4695                 //clear the message we could not handle
4696                 nodes[1].node.get_and_clear_pending_msg_events();
4697         }
4698
4699         #[test]
4700         fn test_update_fee_with_fundee_update_add_htlc() {
4701                 let mut nodes = create_network(2);
4702                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4703                 let channel_id = chan.2;
4704
4705                 // balancing
4706                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4707
4708                 let feerate = get_feerate!(nodes[0], channel_id);
4709                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4710                 check_added_monitors!(nodes[0], 1);
4711
4712                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4713                 assert_eq!(events_0.len(), 1);
4714                 let (update_msg, commitment_signed) = match events_0[0] {
4715                                 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 } } => {
4716                                 (update_fee.as_ref(), commitment_signed)
4717                         },
4718                         _ => panic!("Unexpected event"),
4719                 };
4720                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4721                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4722                 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4723                 check_added_monitors!(nodes[1], 1);
4724
4725                 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
4726
4727                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
4728
4729                 // nothing happens since node[1] is in AwaitingRemoteRevoke
4730                 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
4731                 {
4732                         let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
4733                         assert_eq!(added_monitors.len(), 0);
4734                         added_monitors.clear();
4735                 }
4736                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4737                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4738                 // node[1] has nothing to do
4739
4740                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4741                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4742                 check_added_monitors!(nodes[0], 1);
4743
4744                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4745                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4746                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4747                 check_added_monitors!(nodes[0], 1);
4748                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4749                 check_added_monitors!(nodes[1], 1);
4750                 // AwaitingRemoteRevoke ends here
4751
4752                 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4753                 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
4754                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
4755                 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
4756                 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
4757                 assert_eq!(commitment_update.update_fee.is_none(), true);
4758
4759                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]).unwrap();
4760                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4761                 check_added_monitors!(nodes[0], 1);
4762                 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4763
4764                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke).unwrap();
4765                 check_added_monitors!(nodes[1], 1);
4766                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4767
4768                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed).unwrap();
4769                 check_added_monitors!(nodes[1], 1);
4770                 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4771                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4772
4773                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke).unwrap();
4774                 check_added_monitors!(nodes[0], 1);
4775                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4776
4777                 let events = nodes[0].node.get_and_clear_pending_events();
4778                 assert_eq!(events.len(), 1);
4779                 match events[0] {
4780                         Event::PendingHTLCsForwardable { .. } => { },
4781                         _ => panic!("Unexpected event"),
4782                 };
4783                 nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
4784                 nodes[0].node.process_pending_htlc_forwards();
4785
4786                 let events = nodes[0].node.get_and_clear_pending_events();
4787                 assert_eq!(events.len(), 1);
4788                 match events[0] {
4789                         Event::PaymentReceived { .. } => { },
4790                         _ => panic!("Unexpected event"),
4791                 };
4792
4793                 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
4794
4795                 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
4796                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
4797                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4798         }
4799
4800         #[test]
4801         fn test_update_fee() {
4802                 let nodes = create_network(2);
4803                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4804                 let channel_id = chan.2;
4805
4806                 // A                                        B
4807                 // (1) update_fee/commitment_signed      ->
4808                 //                                       <- (2) revoke_and_ack
4809                 //                                       .- send (3) commitment_signed
4810                 // (4) update_fee/commitment_signed      ->
4811                 //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
4812                 //                                       <- (3) commitment_signed delivered
4813                 // send (6) revoke_and_ack               -.
4814                 //                                       <- (5) deliver revoke_and_ack
4815                 // (6) deliver revoke_and_ack            ->
4816                 //                                       .- send (7) commitment_signed in response to (4)
4817                 //                                       <- (7) deliver commitment_signed
4818                 // revoke_and_ack                        ->
4819
4820                 // Create and deliver (1)...
4821                 let feerate = get_feerate!(nodes[0], channel_id);
4822                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4823                 check_added_monitors!(nodes[0], 1);
4824
4825                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4826                 assert_eq!(events_0.len(), 1);
4827                 let (update_msg, commitment_signed) = match events_0[0] {
4828                                 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 } } => {
4829                                 (update_fee.as_ref(), commitment_signed)
4830                         },
4831                         _ => panic!("Unexpected event"),
4832                 };
4833                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4834
4835                 // Generate (2) and (3):
4836                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4837                 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4838                 check_added_monitors!(nodes[1], 1);
4839
4840                 // Deliver (2):
4841                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4842                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4843                 check_added_monitors!(nodes[0], 1);
4844
4845                 // Create and deliver (4)...
4846                 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
4847                 check_added_monitors!(nodes[0], 1);
4848                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4849                 assert_eq!(events_0.len(), 1);
4850                 let (update_msg, commitment_signed) = match events_0[0] {
4851                                 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 } } => {
4852                                 (update_fee.as_ref(), commitment_signed)
4853                         },
4854                         _ => panic!("Unexpected event"),
4855                 };
4856
4857                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4858                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4859                 check_added_monitors!(nodes[1], 1);
4860                 // ... creating (5)
4861                 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4862                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4863
4864                 // Handle (3), creating (6):
4865                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0).unwrap();
4866                 check_added_monitors!(nodes[0], 1);
4867                 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4868                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4869
4870                 // Deliver (5):
4871                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4872                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4873                 check_added_monitors!(nodes[0], 1);
4874
4875                 // Deliver (6), creating (7):
4876                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0).unwrap();
4877                 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4878                 assert!(commitment_update.update_add_htlcs.is_empty());
4879                 assert!(commitment_update.update_fulfill_htlcs.is_empty());
4880                 assert!(commitment_update.update_fail_htlcs.is_empty());
4881                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
4882                 assert!(commitment_update.update_fee.is_none());
4883                 check_added_monitors!(nodes[1], 1);
4884
4885                 // Deliver (7)
4886                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4887                 check_added_monitors!(nodes[0], 1);
4888                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4889                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4890
4891                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4892                 check_added_monitors!(nodes[1], 1);
4893                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4894
4895                 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
4896                 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
4897                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4898         }
4899
4900         #[test]
4901         fn pre_funding_lock_shutdown_test() {
4902                 // Test sending a shutdown prior to funding_locked after funding generation
4903                 let nodes = create_network(2);
4904                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0);
4905                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4906                 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4907                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4908
4909                 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
4910                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4911                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4912                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4913                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4914
4915                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4916                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4917                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4918                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4919                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4920                 assert!(node_0_none.is_none());
4921
4922                 assert!(nodes[0].node.list_channels().is_empty());
4923                 assert!(nodes[1].node.list_channels().is_empty());
4924         }
4925
4926         #[test]
4927         fn updates_shutdown_wait() {
4928                 // Test sending a shutdown with outstanding updates pending
4929                 let mut nodes = create_network(3);
4930                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4931                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4932                 let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4933                 let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4934
4935                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
4936
4937                 nodes[0].node.close_channel(&chan_1.2).unwrap();
4938                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4939                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4940                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4941                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4942
4943                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4944                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4945
4946                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4947                 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route_1, payment_hash) {}
4948                 else { panic!("New sends should fail!") };
4949                 if let Err(APIError::ChannelUnavailable {..}) = nodes[1].node.send_payment(route_2, payment_hash) {}
4950                 else { panic!("New sends should fail!") };
4951
4952                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
4953                 check_added_monitors!(nodes[2], 1);
4954                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4955                 assert!(updates.update_add_htlcs.is_empty());
4956                 assert!(updates.update_fail_htlcs.is_empty());
4957                 assert!(updates.update_fail_malformed_htlcs.is_empty());
4958                 assert!(updates.update_fee.is_none());
4959                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4960                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
4961                 check_added_monitors!(nodes[1], 1);
4962                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4963                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
4964
4965                 assert!(updates_2.update_add_htlcs.is_empty());
4966                 assert!(updates_2.update_fail_htlcs.is_empty());
4967                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
4968                 assert!(updates_2.update_fee.is_none());
4969                 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
4970                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
4971                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
4972
4973                 let events = nodes[0].node.get_and_clear_pending_events();
4974                 assert_eq!(events.len(), 1);
4975                 match events[0] {
4976                         Event::PaymentSent { ref payment_preimage } => {
4977                                 assert_eq!(our_payment_preimage, *payment_preimage);
4978                         },
4979                         _ => panic!("Unexpected event"),
4980                 }
4981
4982                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4983                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4984                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4985                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4986                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4987                 assert!(node_0_none.is_none());
4988
4989                 assert!(nodes[0].node.list_channels().is_empty());
4990
4991                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4992                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
4993                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
4994                 assert!(nodes[1].node.list_channels().is_empty());
4995                 assert!(nodes[2].node.list_channels().is_empty());
4996         }
4997
4998         #[test]
4999         fn htlc_fail_async_shutdown() {
5000                 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
5001                 let mut nodes = create_network(3);
5002                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5003                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5004
5005                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5006                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5007                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5008                 check_added_monitors!(nodes[0], 1);
5009                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5010                 assert_eq!(updates.update_add_htlcs.len(), 1);
5011                 assert!(updates.update_fulfill_htlcs.is_empty());
5012                 assert!(updates.update_fail_htlcs.is_empty());
5013                 assert!(updates.update_fail_malformed_htlcs.is_empty());
5014                 assert!(updates.update_fee.is_none());
5015
5016                 nodes[1].node.close_channel(&chan_1.2).unwrap();
5017                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5018                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
5019                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5020
5021                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5022                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
5023                 check_added_monitors!(nodes[1], 1);
5024                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
5025                 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
5026
5027                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5028                 assert!(updates_2.update_add_htlcs.is_empty());
5029                 assert!(updates_2.update_fulfill_htlcs.is_empty());
5030                 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
5031                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
5032                 assert!(updates_2.update_fee.is_none());
5033
5034                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]).unwrap();
5035                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
5036
5037                 let events = nodes[0].node.get_and_clear_pending_events();
5038                 assert_eq!(events.len(), 1);
5039                 match events[0] {
5040                         Event::PaymentFailed { ref payment_hash, ref rejected_by_dest } => {
5041                                 assert_eq!(our_payment_hash, *payment_hash);
5042                                 assert!(!rejected_by_dest);
5043                         },
5044                         _ => panic!("Unexpected event"),
5045                 }
5046
5047                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5048                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5049                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5050                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5051                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5052                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5053                 assert!(node_0_none.is_none());
5054
5055                 assert!(nodes[0].node.list_channels().is_empty());
5056
5057                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5058                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5059                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5060                 assert!(nodes[1].node.list_channels().is_empty());
5061                 assert!(nodes[2].node.list_channels().is_empty());
5062         }
5063
5064         fn do_test_shutdown_rebroadcast(recv_count: u8) {
5065                 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
5066                 // messages delivered prior to disconnect
5067                 let nodes = create_network(3);
5068                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5069                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5070
5071                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
5072
5073                 nodes[1].node.close_channel(&chan_1.2).unwrap();
5074                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5075                 if recv_count > 0 {
5076                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
5077                         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5078                         if recv_count > 1 {
5079                                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
5080                         }
5081                 }
5082
5083                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5084                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5085
5086                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5087                 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5088                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5089                 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5090
5091                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish).unwrap();
5092                 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5093                 assert!(node_1_shutdown == node_1_2nd_shutdown);
5094
5095                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish).unwrap();
5096                 let node_0_2nd_shutdown = if recv_count > 0 {
5097                         let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5098                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5099                         node_0_2nd_shutdown
5100                 } else {
5101                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5102                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5103                         get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
5104                 };
5105                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown).unwrap();
5106
5107                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5108                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5109
5110                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
5111                 check_added_monitors!(nodes[2], 1);
5112                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5113                 assert!(updates.update_add_htlcs.is_empty());
5114                 assert!(updates.update_fail_htlcs.is_empty());
5115                 assert!(updates.update_fail_malformed_htlcs.is_empty());
5116                 assert!(updates.update_fee.is_none());
5117                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5118                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
5119                 check_added_monitors!(nodes[1], 1);
5120                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5121                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
5122
5123                 assert!(updates_2.update_add_htlcs.is_empty());
5124                 assert!(updates_2.update_fail_htlcs.is_empty());
5125                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
5126                 assert!(updates_2.update_fee.is_none());
5127                 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
5128                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
5129                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
5130
5131                 let events = nodes[0].node.get_and_clear_pending_events();
5132                 assert_eq!(events.len(), 1);
5133                 match events[0] {
5134                         Event::PaymentSent { ref payment_preimage } => {
5135                                 assert_eq!(our_payment_preimage, *payment_preimage);
5136                         },
5137                         _ => panic!("Unexpected event"),
5138                 }
5139
5140                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5141                 if recv_count > 0 {
5142                         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5143                         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5144                         assert!(node_1_closing_signed.is_some());
5145                 }
5146
5147                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5148                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5149
5150                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5151                 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5152                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5153                 if recv_count == 0 {
5154                         // If all closing_signeds weren't delivered we can just resume where we left off...
5155                         let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5156
5157                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish).unwrap();
5158                         let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5159                         assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
5160
5161                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish).unwrap();
5162                         let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5163                         assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
5164
5165                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown).unwrap();
5166                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5167
5168                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown).unwrap();
5169                         let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5170                         assert!(node_0_closing_signed == node_0_2nd_closing_signed);
5171
5172                         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed).unwrap();
5173                         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5174                         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5175                         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5176                         assert!(node_0_none.is_none());
5177                 } else {
5178                         // If one node, however, received + responded with an identical closing_signed we end
5179                         // up erroring and node[0] will try to broadcast its own latest commitment transaction.
5180                         // There isn't really anything better we can do simply, but in the future we might
5181                         // explore storing a set of recently-closed channels that got disconnected during
5182                         // closing_signed and avoiding broadcasting local commitment txn for some timeout to
5183                         // give our counterparty enough time to (potentially) broadcast a cooperative closing
5184                         // transaction.
5185                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5186
5187                         if let Err(msgs::HandleError{action: Some(msgs::ErrorAction::SendErrorMessage{msg}), ..}) =
5188                                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish) {
5189                                 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
5190                                 let msgs::ErrorMessage {ref channel_id, ..} = msg;
5191                                 assert_eq!(*channel_id, chan_1.2);
5192                         } else { panic!("Needed SendErrorMessage close"); }
5193
5194                         // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
5195                         // checks it, but in this case nodes[0] didn't ever get a chance to receive a
5196                         // closing_signed so we do it ourselves
5197                         let events = nodes[0].node.get_and_clear_pending_msg_events();
5198                         assert_eq!(events.len(), 1);
5199                         match events[0] {
5200                                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5201                                         assert_eq!(msg.contents.flags & 2, 2);
5202                                 },
5203                                 _ => panic!("Unexpected event"),
5204                         }
5205                 }
5206
5207                 assert!(nodes[0].node.list_channels().is_empty());
5208
5209                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5210                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5211                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5212                 assert!(nodes[1].node.list_channels().is_empty());
5213                 assert!(nodes[2].node.list_channels().is_empty());
5214         }
5215
5216         #[test]
5217         fn test_shutdown_rebroadcast() {
5218                 do_test_shutdown_rebroadcast(0);
5219                 do_test_shutdown_rebroadcast(1);
5220                 do_test_shutdown_rebroadcast(2);
5221         }
5222
5223         #[test]
5224         fn fake_network_test() {
5225                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5226                 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
5227                 let nodes = create_network(4);
5228
5229                 // Create some initial channels
5230                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5231                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5232                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5233
5234                 // Rebalance the network a bit by relaying one payment through all the channels...
5235                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5236                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5237                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5238                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5239
5240                 // Send some more payments
5241                 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
5242                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
5243                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
5244
5245                 // Test failure packets
5246                 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
5247                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
5248
5249                 // Add a new channel that skips 3
5250                 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
5251
5252                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
5253                 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
5254                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5255                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5256                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5257                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5258                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5259
5260                 // Do some rebalance loop payments, simultaneously
5261                 let mut hops = Vec::with_capacity(3);
5262                 hops.push(RouteHop {
5263                         pubkey: nodes[2].node.get_our_node_id(),
5264                         short_channel_id: chan_2.0.contents.short_channel_id,
5265                         fee_msat: 0,
5266                         cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
5267                 });
5268                 hops.push(RouteHop {
5269                         pubkey: nodes[3].node.get_our_node_id(),
5270                         short_channel_id: chan_3.0.contents.short_channel_id,
5271                         fee_msat: 0,
5272                         cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
5273                 });
5274                 hops.push(RouteHop {
5275                         pubkey: nodes[1].node.get_our_node_id(),
5276                         short_channel_id: chan_4.0.contents.short_channel_id,
5277                         fee_msat: 1000000,
5278                         cltv_expiry_delta: TEST_FINAL_CLTV,
5279                 });
5280                 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;
5281                 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;
5282                 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
5283
5284                 let mut hops = Vec::with_capacity(3);
5285                 hops.push(RouteHop {
5286                         pubkey: nodes[3].node.get_our_node_id(),
5287                         short_channel_id: chan_4.0.contents.short_channel_id,
5288                         fee_msat: 0,
5289                         cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
5290                 });
5291                 hops.push(RouteHop {
5292                         pubkey: nodes[2].node.get_our_node_id(),
5293                         short_channel_id: chan_3.0.contents.short_channel_id,
5294                         fee_msat: 0,
5295                         cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
5296                 });
5297                 hops.push(RouteHop {
5298                         pubkey: nodes[1].node.get_our_node_id(),
5299                         short_channel_id: chan_2.0.contents.short_channel_id,
5300                         fee_msat: 1000000,
5301                         cltv_expiry_delta: TEST_FINAL_CLTV,
5302                 });
5303                 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;
5304                 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;
5305                 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
5306
5307                 // Claim the rebalances...
5308                 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
5309                 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
5310
5311                 // Add a duplicate new channel from 2 to 4
5312                 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3);
5313
5314                 // Send some payments across both channels
5315                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5316                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5317                 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5318
5319                 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
5320
5321                 //TODO: Test that routes work again here as we've been notified that the channel is full
5322
5323                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
5324                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
5325                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
5326
5327                 // Close down the channels...
5328                 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
5329                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
5330                 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
5331                 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
5332                 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
5333         }
5334
5335         #[test]
5336         fn duplicate_htlc_test() {
5337                 // Test that we accept duplicate payment_hash HTLCs across the network and that
5338                 // claiming/failing them are all separate and don't effect each other
5339                 let mut nodes = create_network(6);
5340
5341                 // Create some initial channels to route via 3 to 4/5 from 0/1/2
5342                 create_announced_chan_between_nodes(&nodes, 0, 3);
5343                 create_announced_chan_between_nodes(&nodes, 1, 3);
5344                 create_announced_chan_between_nodes(&nodes, 2, 3);
5345                 create_announced_chan_between_nodes(&nodes, 3, 4);
5346                 create_announced_chan_between_nodes(&nodes, 3, 5);
5347
5348                 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
5349
5350                 *nodes[0].network_payment_count.borrow_mut() -= 1;
5351                 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
5352
5353                 *nodes[0].network_payment_count.borrow_mut() -= 1;
5354                 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
5355
5356                 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
5357                 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
5358                 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
5359         }
5360
5361         #[derive(PartialEq)]
5362         enum HTLCType { NONE, TIMEOUT, SUCCESS }
5363         /// Tests that the given node has broadcast transactions for the given Channel
5364         ///
5365         /// First checks that the latest local commitment tx has been broadcast, unless an explicit
5366         /// commitment_tx is provided, which may be used to test that a remote commitment tx was
5367         /// broadcast and the revoked outputs were claimed.
5368         ///
5369         /// Next tests that there is (or is not) a transaction that spends the commitment transaction
5370         /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
5371         ///
5372         /// All broadcast transactions must be accounted for in one of the above three types of we'll
5373         /// also fail.
5374         fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
5375                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5376                 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
5377
5378                 let mut res = Vec::with_capacity(2);
5379                 node_txn.retain(|tx| {
5380                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
5381                                 check_spends!(tx, chan.3.clone());
5382                                 if commitment_tx.is_none() {
5383                                         res.push(tx.clone());
5384                                 }
5385                                 false
5386                         } else { true }
5387                 });
5388                 if let Some(explicit_tx) = commitment_tx {
5389                         res.push(explicit_tx.clone());
5390                 }
5391
5392                 assert_eq!(res.len(), 1);
5393
5394                 if has_htlc_tx != HTLCType::NONE {
5395                         node_txn.retain(|tx| {
5396                                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
5397                                         check_spends!(tx, res[0].clone());
5398                                         if has_htlc_tx == HTLCType::TIMEOUT {
5399                                                 assert!(tx.lock_time != 0);
5400                                         } else {
5401                                                 assert!(tx.lock_time == 0);
5402                                         }
5403                                         res.push(tx.clone());
5404                                         false
5405                                 } else { true }
5406                         });
5407                         assert!(res.len() == 2 || res.len() == 3);
5408                         if res.len() == 3 {
5409                                 assert_eq!(res[1], res[2]);
5410                         }
5411                 }
5412
5413                 assert!(node_txn.is_empty());
5414                 res
5415         }
5416
5417         /// Tests that the given node has broadcast a claim transaction against the provided revoked
5418         /// HTLC transaction.
5419         fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
5420                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5421                 assert_eq!(node_txn.len(), 1);
5422                 node_txn.retain(|tx| {
5423                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
5424                                 check_spends!(tx, revoked_tx.clone());
5425                                 false
5426                         } else { true }
5427                 });
5428                 assert!(node_txn.is_empty());
5429         }
5430
5431         fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
5432                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5433
5434                 assert!(node_txn.len() >= 1);
5435                 assert_eq!(node_txn[0].input.len(), 1);
5436                 let mut found_prev = false;
5437
5438                 for tx in prev_txn {
5439                         if node_txn[0].input[0].previous_output.txid == tx.txid() {
5440                                 check_spends!(node_txn[0], tx.clone());
5441                                 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
5442                                 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
5443
5444                                 found_prev = true;
5445                                 break;
5446                         }
5447                 }
5448                 assert!(found_prev);
5449
5450                 let mut res = Vec::new();
5451                 mem::swap(&mut *node_txn, &mut res);
5452                 res
5453         }
5454
5455         fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
5456                 let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
5457                 assert_eq!(events_1.len(), 1);
5458                 let as_update = match events_1[0] {
5459                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5460                                 msg.clone()
5461                         },
5462                         _ => panic!("Unexpected event"),
5463                 };
5464
5465                 let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
5466                 assert_eq!(events_2.len(), 1);
5467                 let bs_update = match events_2[0] {
5468                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5469                                 msg.clone()
5470                         },
5471                         _ => panic!("Unexpected event"),
5472                 };
5473
5474                 for node in nodes {
5475                         node.router.handle_channel_update(&as_update).unwrap();
5476                         node.router.handle_channel_update(&bs_update).unwrap();
5477                 }
5478         }
5479
5480         macro_rules! expect_pending_htlcs_forwardable {
5481                 ($node: expr) => {{
5482                         let events = $node.node.get_and_clear_pending_events();
5483                         assert_eq!(events.len(), 1);
5484                         match events[0] {
5485                                 Event::PendingHTLCsForwardable { .. } => { },
5486                                 _ => panic!("Unexpected event"),
5487                         };
5488                         $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
5489                         $node.node.process_pending_htlc_forwards();
5490                 }}
5491         }
5492
5493         fn do_channel_reserve_test(test_recv: bool) {
5494                 use util::rng;
5495                 use std::sync::atomic::Ordering;
5496                 use ln::msgs::HandleError;
5497
5498                 macro_rules! get_channel_value_stat {
5499                         ($node: expr, $channel_id: expr) => {{
5500                                 let chan_lock = $node.node.channel_state.lock().unwrap();
5501                                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
5502                                 chan.get_value_stat()
5503                         }}
5504                 }
5505
5506                 let mut nodes = create_network(3);
5507                 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001);
5508                 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001);
5509
5510                 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
5511                 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
5512
5513                 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
5514                 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
5515
5516                 macro_rules! get_route_and_payment_hash {
5517                         ($recv_value: expr) => {{
5518                                 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
5519                                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5520                                 (route, payment_hash, payment_preimage)
5521                         }}
5522                 };
5523
5524                 macro_rules! expect_forward {
5525                         ($node: expr) => {{
5526                                 let mut events = $node.node.get_and_clear_pending_msg_events();
5527                                 assert_eq!(events.len(), 1);
5528                                 check_added_monitors!($node, 1);
5529                                 let payment_event = SendEvent::from_event(events.remove(0));
5530                                 payment_event
5531                         }}
5532                 }
5533
5534                 macro_rules! expect_payment_received {
5535                         ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
5536                                 let events = $node.node.get_and_clear_pending_events();
5537                                 assert_eq!(events.len(), 1);
5538                                 match events[0] {
5539                                         Event::PaymentReceived { ref payment_hash, amt } => {
5540                                                 assert_eq!($expected_payment_hash, *payment_hash);
5541                                                 assert_eq!($expected_recv_value, amt);
5542                                         },
5543                                         _ => panic!("Unexpected event"),
5544                                 }
5545                         }
5546                 };
5547
5548                 let feemsat = 239; // somehow we know?
5549                 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
5550
5551                 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
5552
5553                 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
5554                 {
5555                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
5556                         assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
5557                         let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
5558                         match err {
5559                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
5560                                 _ => panic!("Unknown error variants"),
5561                         }
5562                 }
5563
5564                 let mut htlc_id = 0;
5565                 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
5566                 // nodes[0]'s wealth
5567                 loop {
5568                         let amt_msat = recv_value_0 + total_fee_msat;
5569                         if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
5570                                 break;
5571                         }
5572                         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
5573                         htlc_id += 1;
5574
5575                         let (stat01_, stat11_, stat12_, stat22_) = (
5576                                 get_channel_value_stat!(nodes[0], chan_1.2),
5577                                 get_channel_value_stat!(nodes[1], chan_1.2),
5578                                 get_channel_value_stat!(nodes[1], chan_2.2),
5579                                 get_channel_value_stat!(nodes[2], chan_2.2),
5580                         );
5581
5582                         assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
5583                         assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
5584                         assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
5585                         assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
5586                         stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
5587                 }
5588
5589                 {
5590                         let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
5591                         // attempt to get channel_reserve violation
5592                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
5593                         let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
5594                         match err {
5595                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5596                                 _ => panic!("Unknown error variants"),
5597                         }
5598                 }
5599
5600                 // adding pending output
5601                 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
5602                 let amt_msat_1 = recv_value_1 + total_fee_msat;
5603
5604                 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
5605                 let payment_event_1 = {
5606                         nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
5607                         check_added_monitors!(nodes[0], 1);
5608
5609                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5610                         assert_eq!(events.len(), 1);
5611                         SendEvent::from_event(events.remove(0))
5612                 };
5613                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]).unwrap();
5614
5615                 // channel reserve test with htlc pending output > 0
5616                 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
5617                 {
5618                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5619                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5620                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5621                                 _ => panic!("Unknown error variants"),
5622                         }
5623                 }
5624
5625                 {
5626                         // test channel_reserve test on nodes[1] side
5627                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5628
5629                         // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
5630                         let secp_ctx = Secp256k1::new();
5631                         let session_priv = SecretKey::from_slice(&secp_ctx, &{
5632                                 let mut session_key = [0; 32];
5633                                 rng::fill_bytes(&mut session_key);
5634                                 session_key
5635                         }).expect("RNG is bad!");
5636
5637                         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5638                         let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
5639                         let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height).unwrap();
5640                         let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
5641                         let msg = msgs::UpdateAddHTLC {
5642                                 channel_id: chan_1.2,
5643                                 htlc_id,
5644                                 amount_msat: htlc_msat,
5645                                 payment_hash: our_payment_hash,
5646                                 cltv_expiry: htlc_cltv,
5647                                 onion_routing_packet: onion_packet,
5648                         };
5649
5650                         if test_recv {
5651                                 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).err().unwrap();
5652                                 match err {
5653                                         HandleError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
5654                                 }
5655                                 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
5656                                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5657                                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5658                                 let channel_close_broadcast = nodes[1].node.get_and_clear_pending_msg_events();
5659                                 assert_eq!(channel_close_broadcast.len(), 1);
5660                                 match channel_close_broadcast[0] {
5661                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5662                                                 assert_eq!(msg.contents.flags & 2, 2);
5663                                         },
5664                                         _ => panic!("Unexpected event"),
5665                                 }
5666                                 return;
5667                         }
5668                 }
5669
5670                 // split the rest to test holding cell
5671                 let recv_value_21 = recv_value_2/2;
5672                 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
5673                 {
5674                         let stat = get_channel_value_stat!(nodes[0], chan_1.2);
5675                         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);
5676                 }
5677
5678                 // now see if they go through on both sides
5679                 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
5680                 // but this will stuck in the holding cell
5681                 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
5682                 check_added_monitors!(nodes[0], 0);
5683                 let events = nodes[0].node.get_and_clear_pending_events();
5684                 assert_eq!(events.len(), 0);
5685
5686                 // test with outbound holding cell amount > 0
5687                 {
5688                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
5689                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5690                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5691                                 _ => panic!("Unknown error variants"),
5692                         }
5693                 }
5694
5695                 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
5696                 // this will also stuck in the holding cell
5697                 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
5698                 check_added_monitors!(nodes[0], 0);
5699                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
5700                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5701
5702                 // flush the pending htlc
5703                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg).unwrap();
5704                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5705                 check_added_monitors!(nodes[1], 1);
5706
5707                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
5708                 check_added_monitors!(nodes[0], 1);
5709                 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5710
5711                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed).unwrap();
5712                 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
5713                 // No commitment_signed so get_event_msg's assert(len == 1) passes
5714                 check_added_monitors!(nodes[0], 1);
5715
5716                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
5717                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5718                 check_added_monitors!(nodes[1], 1);
5719
5720                 expect_pending_htlcs_forwardable!(nodes[1]);
5721
5722                 let ref payment_event_11 = expect_forward!(nodes[1]);
5723                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]).unwrap();
5724                 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
5725
5726                 expect_pending_htlcs_forwardable!(nodes[2]);
5727                 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
5728
5729                 // flush the htlcs in the holding cell
5730                 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
5731                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]).unwrap();
5732                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]).unwrap();
5733                 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
5734                 expect_pending_htlcs_forwardable!(nodes[1]);
5735
5736                 let ref payment_event_3 = expect_forward!(nodes[1]);
5737                 assert_eq!(payment_event_3.msgs.len(), 2);
5738                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]).unwrap();
5739                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]).unwrap();
5740
5741                 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
5742                 expect_pending_htlcs_forwardable!(nodes[2]);
5743
5744                 let events = nodes[2].node.get_and_clear_pending_events();
5745                 assert_eq!(events.len(), 2);
5746                 match events[0] {
5747                         Event::PaymentReceived { ref payment_hash, amt } => {
5748                                 assert_eq!(our_payment_hash_21, *payment_hash);
5749                                 assert_eq!(recv_value_21, amt);
5750                         },
5751                         _ => panic!("Unexpected event"),
5752                 }
5753                 match events[1] {
5754                         Event::PaymentReceived { ref payment_hash, amt } => {
5755                                 assert_eq!(our_payment_hash_22, *payment_hash);
5756                                 assert_eq!(recv_value_22, amt);
5757                         },
5758                         _ => panic!("Unexpected event"),
5759                 }
5760
5761                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
5762                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
5763                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
5764
5765                 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);
5766                 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
5767                 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
5768                 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
5769
5770                 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
5771                 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
5772         }
5773
5774         #[test]
5775         fn channel_reserve_test() {
5776                 do_channel_reserve_test(false);
5777                 do_channel_reserve_test(true);
5778         }
5779
5780         #[test]
5781         fn channel_monitor_network_test() {
5782                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5783                 // tests that ChannelMonitor is able to recover from various states.
5784                 let nodes = create_network(5);
5785
5786                 // Create some initial channels
5787                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5788                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5789                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5790                 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5791
5792                 // Rebalance the network a bit by relaying one payment through all the channels...
5793                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5794                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5795                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5796                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5797
5798                 // Simple case with no pending HTLCs:
5799                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
5800                 {
5801                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
5802                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5803                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5804                         test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
5805                 }
5806                 get_announce_close_broadcast_events(&nodes, 0, 1);
5807                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5808                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5809
5810                 // One pending HTLC is discarded by the force-close:
5811                 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
5812
5813                 // Simple case of one pending HTLC to HTLC-Timeout
5814                 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
5815                 {
5816                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
5817                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5818                         nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5819                         test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
5820                 }
5821                 get_announce_close_broadcast_events(&nodes, 1, 2);
5822                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5823                 assert_eq!(nodes[2].node.list_channels().len(), 1);
5824
5825                 macro_rules! claim_funds {
5826                         ($node: expr, $prev_node: expr, $preimage: expr) => {
5827                                 {
5828                                         assert!($node.node.claim_funds($preimage));
5829                                         check_added_monitors!($node, 1);
5830
5831                                         let events = $node.node.get_and_clear_pending_msg_events();
5832                                         assert_eq!(events.len(), 1);
5833                                         match events[0] {
5834                                                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
5835                                                         assert!(update_add_htlcs.is_empty());
5836                                                         assert!(update_fail_htlcs.is_empty());
5837                                                         assert_eq!(*node_id, $prev_node.node.get_our_node_id());
5838                                                 },
5839                                                 _ => panic!("Unexpected event"),
5840                                         };
5841                                 }
5842                         }
5843                 }
5844
5845                 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
5846                 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
5847                 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
5848                 {
5849                         let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
5850
5851                         // Claim the payment on nodes[3], giving it knowledge of the preimage
5852                         claim_funds!(nodes[3], nodes[2], payment_preimage_1);
5853
5854                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5855                         nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
5856
5857                         check_preimage_claim(&nodes[3], &node_txn);
5858                 }
5859                 get_announce_close_broadcast_events(&nodes, 2, 3);
5860                 assert_eq!(nodes[2].node.list_channels().len(), 0);
5861                 assert_eq!(nodes[3].node.list_channels().len(), 1);
5862
5863                 { // Cheat and reset nodes[4]'s height to 1
5864                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5865                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![] }, 1);
5866                 }
5867
5868                 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
5869                 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
5870                 // One pending HTLC to time out:
5871                 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
5872                 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
5873                 // buffer space).
5874
5875                 {
5876                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5877                         nodes[3].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5878                         for i in 3..TEST_FINAL_CLTV + 2 + HTLC_FAIL_TIMEOUT_BLOCKS + 1 {
5879                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5880                                 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5881                         }
5882
5883                         let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
5884
5885                         // Claim the payment on nodes[4], giving it knowledge of the preimage
5886                         claim_funds!(nodes[4], nodes[3], payment_preimage_2);
5887
5888                         header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5889                         nodes[4].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5890                         for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
5891                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5892                                 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5893                         }
5894
5895                         test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
5896
5897                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5898                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
5899
5900                         check_preimage_claim(&nodes[4], &node_txn);
5901                 }
5902                 get_announce_close_broadcast_events(&nodes, 3, 4);
5903                 assert_eq!(nodes[3].node.list_channels().len(), 0);
5904                 assert_eq!(nodes[4].node.list_channels().len(), 0);
5905         }
5906
5907         #[test]
5908         fn test_justice_tx() {
5909                 // Test justice txn built on revoked HTLC-Success tx, against both sides
5910
5911                 let nodes = create_network(2);
5912                 // Create some new channels:
5913                 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
5914
5915                 // A pending HTLC which will be revoked:
5916                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5917                 // Get the will-be-revoked local txn from nodes[0]
5918                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5919                 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
5920                 assert_eq!(revoked_local_txn[0].input.len(), 1);
5921                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
5922                 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
5923                 assert_eq!(revoked_local_txn[1].input.len(), 1);
5924                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
5925                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
5926                 // Revoke the old state
5927                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
5928
5929                 {
5930                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5931                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5932                         {
5933                                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5934                                 assert_eq!(node_txn.len(), 3);
5935                                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5936                                 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
5937
5938                                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5939                                 node_txn.swap_remove(0);
5940                         }
5941                         test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
5942
5943                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5944                         let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
5945                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5946                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5947                         test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
5948                 }
5949                 get_announce_close_broadcast_events(&nodes, 0, 1);
5950
5951                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5952                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5953
5954                 // We test justice_tx build by A on B's revoked HTLC-Success tx
5955                 // Create some new channels:
5956                 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
5957
5958                 // A pending HTLC which will be revoked:
5959                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5960                 // Get the will-be-revoked local txn from B
5961                 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5962                 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
5963                 assert_eq!(revoked_local_txn[0].input.len(), 1);
5964                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
5965                 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
5966                 // Revoke the old state
5967                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
5968                 {
5969                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5970                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5971                         {
5972                                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5973                                 assert_eq!(node_txn.len(), 3);
5974                                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5975                                 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
5976
5977                                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5978                                 node_txn.swap_remove(0);
5979                         }
5980                         test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
5981
5982                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5983                         let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
5984                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5985                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5986                         test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone());
5987                 }
5988                 get_announce_close_broadcast_events(&nodes, 0, 1);
5989                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5990                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5991         }
5992
5993         #[test]
5994         fn revoked_output_claim() {
5995                 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
5996                 // transaction is broadcast by its counterparty
5997                 let nodes = create_network(2);
5998                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5999                 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
6000                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6001                 assert_eq!(revoked_local_txn.len(), 1);
6002                 // Only output is the full channel value back to nodes[0]:
6003                 assert_eq!(revoked_local_txn[0].output.len(), 1);
6004                 // Send a payment through, updating everyone's latest commitment txn
6005                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
6006
6007                 // Inform nodes[1] that nodes[0] broadcast a stale tx
6008                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6009                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6010                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6011                 assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
6012
6013                 assert_eq!(node_txn[0], node_txn[2]);
6014
6015                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
6016                 check_spends!(node_txn[1], chan_1.3.clone());
6017
6018                 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
6019                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6020                 get_announce_close_broadcast_events(&nodes, 0, 1);
6021         }
6022
6023         #[test]
6024         fn claim_htlc_outputs_shared_tx() {
6025                 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
6026                 let nodes = create_network(2);
6027
6028                 // Create some new channel:
6029                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6030
6031                 // Rebalance the network to generate htlc in the two directions
6032                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6033                 // 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
6034                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6035                 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6036
6037                 // Get the will-be-revoked local txn from node[0]
6038                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6039                 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
6040                 assert_eq!(revoked_local_txn[0].input.len(), 1);
6041                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
6042                 assert_eq!(revoked_local_txn[1].input.len(), 1);
6043                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
6044                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
6045                 check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
6046
6047                 //Revoke the old state
6048                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6049
6050                 {
6051                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6052                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6053                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6054
6055                         let events = nodes[1].node.get_and_clear_pending_events();
6056                         assert_eq!(events.len(), 1);
6057                         match events[0] {
6058                                 Event::PaymentFailed { payment_hash, .. } => {
6059                                         assert_eq!(payment_hash, payment_hash_2);
6060                                 },
6061                                 _ => panic!("Unexpected event"),
6062                         }
6063
6064                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6065                         assert_eq!(node_txn.len(), 4);
6066
6067                         assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
6068                         check_spends!(node_txn[0], revoked_local_txn[0].clone());
6069
6070                         assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
6071
6072                         let mut witness_lens = BTreeSet::new();
6073                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6074                         witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
6075                         witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
6076                         assert_eq!(witness_lens.len(), 3);
6077                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6078                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
6079                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
6080
6081                         // Next nodes[1] broadcasts its current local tx state:
6082                         assert_eq!(node_txn[1].input.len(), 1);
6083                         assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
6084
6085                         assert_eq!(node_txn[2].input.len(), 1);
6086                         let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
6087                         assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
6088                         assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
6089                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6090                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
6091                 }
6092                 get_announce_close_broadcast_events(&nodes, 0, 1);
6093                 assert_eq!(nodes[0].node.list_channels().len(), 0);
6094                 assert_eq!(nodes[1].node.list_channels().len(), 0);
6095         }
6096
6097         #[test]
6098         fn claim_htlc_outputs_single_tx() {
6099                 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
6100                 let nodes = create_network(2);
6101
6102                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6103
6104                 // Rebalance the network to generate htlc in the two directions
6105                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6106                 // 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
6107                 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
6108                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6109                 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6110
6111                 // Get the will-be-revoked local txn from node[0]
6112                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6113
6114                 //Revoke the old state
6115                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6116
6117                 {
6118                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6119                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6120                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6121
6122                         let events = nodes[1].node.get_and_clear_pending_events();
6123                         assert_eq!(events.len(), 1);
6124                         match events[0] {
6125                                 Event::PaymentFailed { payment_hash, .. } => {
6126                                         assert_eq!(payment_hash, payment_hash_2);
6127                                 },
6128                                 _ => panic!("Unexpected event"),
6129                         }
6130
6131                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6132                         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)
6133
6134                         assert_eq!(node_txn[0], node_txn[7]);
6135                         assert_eq!(node_txn[1], node_txn[8]);
6136                         assert_eq!(node_txn[2], node_txn[9]);
6137                         assert_eq!(node_txn[3], node_txn[10]);
6138                         assert_eq!(node_txn[4], node_txn[11]);
6139                         assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcated by ChannelManger
6140                         assert_eq!(node_txn[4], node_txn[6]);
6141
6142                         assert_eq!(node_txn[0].input.len(), 1);
6143                         assert_eq!(node_txn[1].input.len(), 1);
6144                         assert_eq!(node_txn[2].input.len(), 1);
6145
6146                         let mut revoked_tx_map = HashMap::new();
6147                         revoked_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
6148                         node_txn[0].verify(&revoked_tx_map).unwrap();
6149                         node_txn[1].verify(&revoked_tx_map).unwrap();
6150                         node_txn[2].verify(&revoked_tx_map).unwrap();
6151
6152                         let mut witness_lens = BTreeSet::new();
6153                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6154                         witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
6155                         witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
6156                         assert_eq!(witness_lens.len(), 3);
6157                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6158                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
6159                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
6160
6161                         assert_eq!(node_txn[3].input.len(), 1);
6162                         check_spends!(node_txn[3], chan_1.3.clone());
6163
6164                         assert_eq!(node_txn[4].input.len(), 1);
6165                         let witness_script = node_txn[4].input[0].witness.last().unwrap();
6166                         assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
6167                         assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
6168                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6169                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
6170                 }
6171                 get_announce_close_broadcast_events(&nodes, 0, 1);
6172                 assert_eq!(nodes[0].node.list_channels().len(), 0);
6173                 assert_eq!(nodes[1].node.list_channels().len(), 0);
6174         }
6175
6176         #[test]
6177         fn test_htlc_on_chain_success() {
6178                 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
6179                 // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
6180                 // broadcasting the right event to other nodes in payment path.
6181                 // A --------------------> B ----------------------> C (preimage)
6182                 // First, C should claim the HTLC output via HTLC-Success when its own latest local
6183                 // commitment transaction was broadcast.
6184                 // Then, B should learn the preimage from said transactions, attempting to claim backwards
6185                 // towards B.
6186                 // B should be able to claim via preimage if A then broadcasts its local tx.
6187                 // Finally, when A sees B's latest local commitment transaction it should be able to claim
6188                 // the HTLC output via the preimage it learned (which, once confirmed should generate a
6189                 // PaymentSent event).
6190
6191                 let nodes = create_network(3);
6192
6193                 // Create some initial channels
6194                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6195                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6196
6197                 // Rebalance the network a bit by relaying one payment through all the channels...
6198                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6199                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6200
6201                 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
6202                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6203
6204                 // Broadcast legit commitment tx from C on B's chain
6205                 // Broadcast HTLC Success transation by C on received output from C's commitment tx on B's chain
6206                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6207                 assert_eq!(commitment_tx.len(), 1);
6208                 check_spends!(commitment_tx[0], chan_2.3.clone());
6209                 nodes[2].node.claim_funds(our_payment_preimage);
6210                 check_added_monitors!(nodes[2], 1);
6211                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6212                 assert!(updates.update_add_htlcs.is_empty());
6213                 assert!(updates.update_fail_htlcs.is_empty());
6214                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6215                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
6216
6217                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6218                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6219                 assert_eq!(events.len(), 1);
6220                 match events[0] {
6221                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6222                         _ => panic!("Unexpected event"),
6223                 }
6224                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
6225                 assert_eq!(node_txn.len(), 3);
6226                 assert_eq!(node_txn[1], commitment_tx[0]);
6227                 assert_eq!(node_txn[0], node_txn[2]);
6228                 check_spends!(node_txn[0], commitment_tx[0].clone());
6229                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6230                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6231                 assert_eq!(node_txn[0].lock_time, 0);
6232
6233                 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
6234                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: node_txn}, 1);
6235                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6236                 {
6237                         let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
6238                         assert_eq!(added_monitors.len(), 1);
6239                         assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
6240                         added_monitors.clear();
6241                 }
6242                 assert_eq!(events.len(), 2);
6243                 match events[0] {
6244                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6245                         _ => panic!("Unexpected event"),
6246                 }
6247                 match events[1] {
6248                         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, .. } } => {
6249                                 assert!(update_add_htlcs.is_empty());
6250                                 assert!(update_fail_htlcs.is_empty());
6251                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6252                                 assert!(update_fail_malformed_htlcs.is_empty());
6253                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6254                         },
6255                         _ => panic!("Unexpected event"),
6256                 };
6257                 {
6258                         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
6259                         // commitment transaction with a corresponding HTLC-Timeout transaction, as well as a
6260                         // timeout-claim of the output that nodes[2] just claimed via success.
6261                         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)
6262                         assert_eq!(node_txn.len(), 4);
6263                         assert_eq!(node_txn[0], node_txn[3]);
6264                         check_spends!(node_txn[0], commitment_tx[0].clone());
6265                         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6266                         assert_ne!(node_txn[0].lock_time, 0);
6267                         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
6268                         check_spends!(node_txn[1], chan_2.3.clone());
6269                         check_spends!(node_txn[2], node_txn[1].clone());
6270                         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6271                         assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6272                         assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6273                         assert_ne!(node_txn[2].lock_time, 0);
6274                         node_txn.clear();
6275                 }
6276
6277                 // Broadcast legit commitment tx from A on B's chain
6278                 // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
6279                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6280                 check_spends!(commitment_tx[0], chan_1.3.clone());
6281                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6282                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6283                 assert_eq!(events.len(), 1);
6284                 match events[0] {
6285                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6286                         _ => panic!("Unexpected event"),
6287                 }
6288                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 1 (HTLC-Success) * 2 (block-rescan)
6289                 assert_eq!(node_txn.len(), 3);
6290                 assert_eq!(node_txn[0], node_txn[2]);
6291                 check_spends!(node_txn[0], commitment_tx[0].clone());
6292                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6293                 assert_eq!(node_txn[0].lock_time, 0);
6294                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
6295                 check_spends!(node_txn[1], chan_1.3.clone());
6296                 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6297                 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
6298                 // we already checked the same situation with A.
6299
6300                 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
6301                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
6302                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6303                 assert_eq!(events.len(), 1);
6304                 match events[0] {
6305                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6306                         _ => panic!("Unexpected event"),
6307                 }
6308                 let events = nodes[0].node.get_and_clear_pending_events();
6309                 assert_eq!(events.len(), 1);
6310                 match events[0] {
6311                         Event::PaymentSent { payment_preimage } => {
6312                                 assert_eq!(payment_preimage, our_payment_preimage);
6313                         },
6314                         _ => panic!("Unexpected event"),
6315                 }
6316                 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)
6317                 assert_eq!(node_txn.len(), 4);
6318                 assert_eq!(node_txn[0], node_txn[3]);
6319                 check_spends!(node_txn[0], commitment_tx[0].clone());
6320                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6321                 assert_ne!(node_txn[0].lock_time, 0);
6322                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6323                 check_spends!(node_txn[1], chan_1.3.clone());
6324                 check_spends!(node_txn[2], node_txn[1].clone());
6325                 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6326                 assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6327                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6328                 assert_ne!(node_txn[2].lock_time, 0);
6329         }
6330
6331         #[test]
6332         fn test_htlc_on_chain_timeout() {
6333                 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
6334                 // ChainWatchInterface and timeout the HTLC  bacward accordingly. So here we test that ChannelManager is
6335                 // broadcasting the right event to other nodes in payment path.
6336                 // A ------------------> B ----------------------> C (timeout)
6337                 //    B's commitment tx                 C's commitment tx
6338                 //            \                                  \
6339                 //         B's HTLC timeout tx               B's timeout tx
6340
6341                 let nodes = create_network(3);
6342
6343                 // Create some intial channels
6344                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6345                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6346
6347                 // Rebalance the network a bit by relaying one payment thorugh all the channels...
6348                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6349                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6350
6351                 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
6352                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6353
6354                 // Brodacast legit commitment tx from C on B's chain
6355                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6356                 check_spends!(commitment_tx[0], chan_2.3.clone());
6357                 nodes[2].node.fail_htlc_backwards(&payment_hash, PaymentFailReason::PreimageUnknown);
6358                 {
6359                         let mut added_monitors = nodes[2].chan_monitor.added_monitors.lock().unwrap();
6360                         assert_eq!(added_monitors.len(), 1);
6361                         added_monitors.clear();
6362                 }
6363                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6364                 assert_eq!(events.len(), 1);
6365                 match events[0] {
6366                         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, .. } } => {
6367                                 assert!(update_add_htlcs.is_empty());
6368                                 assert!(!update_fail_htlcs.is_empty());
6369                                 assert!(update_fulfill_htlcs.is_empty());
6370                                 assert!(update_fail_malformed_htlcs.is_empty());
6371                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
6372                         },
6373                         _ => panic!("Unexpected event"),
6374                 };
6375                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6376                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6377                 assert_eq!(events.len(), 1);
6378                 match events[0] {
6379                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6380                         _ => panic!("Unexpected event"),
6381                 }
6382                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
6383                 assert_eq!(node_txn.len(), 1);
6384                 check_spends!(node_txn[0], chan_2.3.clone());
6385                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
6386
6387                 // Broadcast timeout transaction by B on received output fron C's commitment tx on B's chain
6388                 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
6389                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6390                 let timeout_tx;
6391                 {
6392                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6393                         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)
6394                         assert_eq!(node_txn[0], node_txn[5]);
6395                         assert_eq!(node_txn[1], node_txn[6]);
6396                         assert_eq!(node_txn[2], node_txn[7]);
6397                         check_spends!(node_txn[0], commitment_tx[0].clone());
6398                         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6399                         check_spends!(node_txn[1], chan_2.3.clone());
6400                         check_spends!(node_txn[2], node_txn[1].clone());
6401                         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6402                         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6403                         check_spends!(node_txn[3], chan_2.3.clone());
6404                         check_spends!(node_txn[4], node_txn[3].clone());
6405                         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
6406                         assert_eq!(node_txn[4].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6407                         timeout_tx = node_txn[0].clone();
6408                         node_txn.clear();
6409                 }
6410
6411                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![timeout_tx]}, 1);
6412                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6413                 check_added_monitors!(nodes[1], 1);
6414                 assert_eq!(events.len(), 2);
6415                 match events[0] {
6416                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6417                         _ => panic!("Unexpected event"),
6418                 }
6419                 match events[1] {
6420                         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, .. } } => {
6421                                 assert!(update_add_htlcs.is_empty());
6422                                 assert!(!update_fail_htlcs.is_empty());
6423                                 assert!(update_fulfill_htlcs.is_empty());
6424                                 assert!(update_fail_malformed_htlcs.is_empty());
6425                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6426                         },
6427                         _ => panic!("Unexpected event"),
6428                 };
6429                 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
6430                 assert_eq!(node_txn.len(), 0);
6431
6432                 // Broadcast legit commitment tx from B on A's chain
6433                 let commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6434                 check_spends!(commitment_tx[0], chan_1.3.clone());
6435
6436                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6437                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6438                 assert_eq!(events.len(), 1);
6439                 match events[0] {
6440                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6441                         _ => panic!("Unexpected event"),
6442                 }
6443                 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
6444                 assert_eq!(node_txn.len(), 4);
6445                 assert_eq!(node_txn[0], node_txn[3]);
6446                 check_spends!(node_txn[0], commitment_tx[0].clone());
6447                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6448                 check_spends!(node_txn[1], chan_1.3.clone());
6449                 check_spends!(node_txn[2], node_txn[1].clone());
6450                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6451                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6452         }
6453
6454         #[test]
6455         fn test_simple_commitment_revoked_fail_backward() {
6456                 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
6457                 // and fail backward accordingly.
6458
6459                 let nodes = create_network(3);
6460
6461                 // Create some initial channels
6462                 create_announced_chan_between_nodes(&nodes, 0, 1);
6463                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6464
6465                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6466                 // Get the will-be-revoked local txn from nodes[2]
6467                 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6468                 // Revoke the old state
6469                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6470
6471                 route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6472
6473                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6474                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6475                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6476                 check_added_monitors!(nodes[1], 1);
6477                 assert_eq!(events.len(), 2);
6478                 match events[0] {
6479                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6480                         _ => panic!("Unexpected event"),
6481                 }
6482                 match events[1] {
6483                         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, .. } } => {
6484                                 assert!(update_add_htlcs.is_empty());
6485                                 assert_eq!(update_fail_htlcs.len(), 1);
6486                                 assert!(update_fulfill_htlcs.is_empty());
6487                                 assert!(update_fail_malformed_htlcs.is_empty());
6488                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6489
6490                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6491                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6492
6493                                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6494                                 assert_eq!(events.len(), 1);
6495                                 match events[0] {
6496                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6497                                         _ => panic!("Unexpected event"),
6498                                 }
6499                                 let events = nodes[0].node.get_and_clear_pending_events();
6500                                 assert_eq!(events.len(), 1);
6501                                 match events[0] {
6502                                         Event::PaymentFailed { .. } => {},
6503                                         _ => panic!("Unexpected event"),
6504                                 }
6505                         },
6506                         _ => panic!("Unexpected event"),
6507                 }
6508         }
6509
6510         fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool) {
6511                 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
6512                 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
6513                 // commitment transaction anymore.
6514                 // To do this, we have the peer which will broadcast a revoked commitment transaction send
6515                 // a number of update_fail/commitment_signed updates without ever sending the RAA in
6516                 // response to our commitment_signed. This is somewhat misbehavior-y, though not
6517                 // technically disallowed and we should probably handle it reasonably.
6518                 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
6519                 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
6520                 // transactions:
6521                 // * Once we move it out of our holding cell/add it, we will immediately include it in a
6522                 //   commitment_signed (implying it will be in the latest remote commitment transaction).
6523                 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
6524                 //   and once they revoke the previous commitment transaction (allowing us to send a new
6525                 //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
6526                 let mut nodes = create_network(3);
6527
6528                 // Create some initial channels
6529                 create_announced_chan_between_nodes(&nodes, 0, 1);
6530                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6531
6532                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6533                 // Get the will-be-revoked local txn from nodes[2]
6534                 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6535                 // Revoke the old state
6536                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6537
6538                 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6539                 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6540                 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6541
6542                 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, PaymentFailReason::PreimageUnknown));
6543                 check_added_monitors!(nodes[2], 1);
6544                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6545                 assert!(updates.update_add_htlcs.is_empty());
6546                 assert!(updates.update_fulfill_htlcs.is_empty());
6547                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6548                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6549                 assert!(updates.update_fee.is_none());
6550                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6551                 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
6552                 // Drop the last RAA from 3 -> 2
6553
6554                 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, PaymentFailReason::PreimageUnknown));
6555                 check_added_monitors!(nodes[2], 1);
6556                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6557                 assert!(updates.update_add_htlcs.is_empty());
6558                 assert!(updates.update_fulfill_htlcs.is_empty());
6559                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6560                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6561                 assert!(updates.update_fee.is_none());
6562                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6563                 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6564                 check_added_monitors!(nodes[1], 1);
6565                 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
6566                 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6567                 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6568                 check_added_monitors!(nodes[2], 1);
6569
6570                 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, PaymentFailReason::PreimageUnknown));
6571                 check_added_monitors!(nodes[2], 1);
6572                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6573                 assert!(updates.update_add_htlcs.is_empty());
6574                 assert!(updates.update_fulfill_htlcs.is_empty());
6575                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6576                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6577                 assert!(updates.update_fee.is_none());
6578                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6579                 // At this point first_payment_hash has dropped out of the latest two commitment
6580                 // transactions that nodes[1] is tracking...
6581                 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6582                 check_added_monitors!(nodes[1], 1);
6583                 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
6584                 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6585                 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6586                 check_added_monitors!(nodes[2], 1);
6587
6588                 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
6589                 // on nodes[2]'s RAA.
6590                 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
6591                 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6592                 nodes[1].node.send_payment(route, fourth_payment_hash).unwrap();
6593                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
6594                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6595                 check_added_monitors!(nodes[1], 0);
6596
6597                 if deliver_bs_raa {
6598                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa).unwrap();
6599                         // One monitor for the new revocation preimage, one as we generate a commitment for
6600                         // nodes[0] to fail first_payment_hash backwards.
6601                         check_added_monitors!(nodes[1], 2);
6602                 }
6603
6604                 let mut failed_htlcs = HashSet::new();
6605                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6606
6607                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6608                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6609
6610                 let events = nodes[1].node.get_and_clear_pending_events();
6611                 assert_eq!(events.len(), 1);
6612                 match events[0] {
6613                         Event::PaymentFailed { ref payment_hash, .. } => {
6614                                 assert_eq!(*payment_hash, fourth_payment_hash);
6615                         },
6616                         _ => panic!("Unexpected event"),
6617                 }
6618
6619                 if !deliver_bs_raa {
6620                         // If we delivered the RAA already then we already failed first_payment_hash backwards.
6621                         check_added_monitors!(nodes[1], 1);
6622                 }
6623
6624                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6625                 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
6626                 match events[if deliver_bs_raa { 2 } else { 0 }] {
6627                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6628                         _ => panic!("Unexpected event"),
6629                 }
6630                 if deliver_bs_raa {
6631                         match events[0] {
6632                                 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, .. } } => {
6633                                         assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
6634                                         assert_eq!(update_add_htlcs.len(), 1);
6635                                         assert!(update_fulfill_htlcs.is_empty());
6636                                         assert!(update_fail_htlcs.is_empty());
6637                                         assert!(update_fail_malformed_htlcs.is_empty());
6638                                 },
6639                                 _ => panic!("Unexpected event"),
6640                         }
6641                 }
6642                 // Due to the way backwards-failing occurs we do the updates in two steps.
6643                 let updates = match events[1] {
6644                         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, .. } } => {
6645                                 assert!(update_add_htlcs.is_empty());
6646                                 assert_eq!(update_fail_htlcs.len(), 1);
6647                                 assert!(update_fulfill_htlcs.is_empty());
6648                                 assert!(update_fail_malformed_htlcs.is_empty());
6649                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6650
6651                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6652                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
6653                                 check_added_monitors!(nodes[0], 1);
6654                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6655                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6656                                 check_added_monitors!(nodes[1], 1);
6657                                 let bs_second_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6658                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
6659                                 check_added_monitors!(nodes[1], 1);
6660                                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6661                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6662                                 check_added_monitors!(nodes[0], 1);
6663
6664                                 if !deliver_bs_raa {
6665                                         // If we delievered B's RAA we got an unknown preimage error, not something
6666                                         // that we should update our routing table for.
6667                                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6668                                         assert_eq!(events.len(), 1);
6669                                         match events[0] {
6670                                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6671                                                 _ => panic!("Unexpected event"),
6672                                         }
6673                                 }
6674                                 let events = nodes[0].node.get_and_clear_pending_events();
6675                                 assert_eq!(events.len(), 1);
6676                                 match events[0] {
6677                                         Event::PaymentFailed { ref payment_hash, .. } => {
6678                                                 assert!(failed_htlcs.insert(payment_hash.0));
6679                                         },
6680                                         _ => panic!("Unexpected event"),
6681                                 }
6682
6683                                 bs_second_update
6684                         },
6685                         _ => panic!("Unexpected event"),
6686                 };
6687
6688                 assert!(updates.update_add_htlcs.is_empty());
6689                 assert_eq!(updates.update_fail_htlcs.len(), 2);
6690                 assert!(updates.update_fulfill_htlcs.is_empty());
6691                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6692                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6693                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[1]).unwrap();
6694                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6695
6696                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6697                 assert_eq!(events.len(), 2);
6698                 for event in events {
6699                         match event {
6700                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6701                                 _ => panic!("Unexpected event"),
6702                         }
6703                 }
6704
6705                 let events = nodes[0].node.get_and_clear_pending_events();
6706                 assert_eq!(events.len(), 2);
6707                 match events[0] {
6708                         Event::PaymentFailed { ref payment_hash, .. } => {
6709                                 assert!(failed_htlcs.insert(payment_hash.0));
6710                         },
6711                         _ => panic!("Unexpected event"),
6712                 }
6713                 match events[1] {
6714                         Event::PaymentFailed { ref payment_hash, .. } => {
6715                                 assert!(failed_htlcs.insert(payment_hash.0));
6716                         },
6717                         _ => panic!("Unexpected event"),
6718                 }
6719
6720                 assert!(failed_htlcs.contains(&first_payment_hash.0));
6721                 assert!(failed_htlcs.contains(&second_payment_hash.0));
6722                 assert!(failed_htlcs.contains(&third_payment_hash.0));
6723         }
6724
6725         #[test]
6726         fn test_commitment_revoked_fail_backward_exhaustive() {
6727                 do_test_commitment_revoked_fail_backward_exhaustive(false);
6728                 do_test_commitment_revoked_fail_backward_exhaustive(true);
6729         }
6730
6731         #[test]
6732         fn test_htlc_ignore_latest_remote_commitment() {
6733                 // Test that HTLC transactions spending the latest remote commitment transaction are simply
6734                 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
6735                 let nodes = create_network(2);
6736                 create_announced_chan_between_nodes(&nodes, 0, 1);
6737
6738                 route_payment(&nodes[0], &[&nodes[1]], 10000000);
6739                 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
6740                 {
6741                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6742                         assert_eq!(events.len(), 1);
6743                         match events[0] {
6744                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6745                                         assert_eq!(flags & 0b10, 0b10);
6746                                 },
6747                                 _ => panic!("Unexpected event"),
6748                         }
6749                 }
6750
6751                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6752                 assert_eq!(node_txn.len(), 2);
6753
6754                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6755                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6756
6757                 {
6758                         let events = nodes[1].node.get_and_clear_pending_msg_events();
6759                         assert_eq!(events.len(), 1);
6760                         match events[0] {
6761                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6762                                         assert_eq!(flags & 0b10, 0b10);
6763                                 },
6764                                 _ => panic!("Unexpected event"),
6765                         }
6766                 }
6767
6768                 // Duplicate the block_connected call since this may happen due to other listeners
6769                 // registering new transactions
6770                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6771         }
6772
6773         #[test]
6774         fn test_force_close_fail_back() {
6775                 // Check which HTLCs are failed-backwards on channel force-closure
6776                 let mut nodes = create_network(3);
6777                 create_announced_chan_between_nodes(&nodes, 0, 1);
6778                 create_announced_chan_between_nodes(&nodes, 1, 2);
6779
6780                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
6781
6782                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6783
6784                 let mut payment_event = {
6785                         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6786                         check_added_monitors!(nodes[0], 1);
6787
6788                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6789                         assert_eq!(events.len(), 1);
6790                         SendEvent::from_event(events.remove(0))
6791                 };
6792
6793                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6794                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6795
6796                 let events_1 = nodes[1].node.get_and_clear_pending_events();
6797                 assert_eq!(events_1.len(), 1);
6798                 match events_1[0] {
6799                         Event::PendingHTLCsForwardable { .. } => { },
6800                         _ => panic!("Unexpected event"),
6801                 };
6802
6803                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
6804                 nodes[1].node.process_pending_htlc_forwards();
6805
6806                 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6807                 assert_eq!(events_2.len(), 1);
6808                 payment_event = SendEvent::from_event(events_2.remove(0));
6809                 assert_eq!(payment_event.msgs.len(), 1);
6810
6811                 check_added_monitors!(nodes[1], 1);
6812                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6813                 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
6814                 check_added_monitors!(nodes[2], 1);
6815                 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6816
6817                 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
6818                 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
6819                 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
6820
6821                 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
6822                 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6823                 assert_eq!(events_3.len(), 1);
6824                 match events_3[0] {
6825                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6826                                 assert_eq!(flags & 0b10, 0b10);
6827                         },
6828                         _ => panic!("Unexpected event"),
6829                 }
6830
6831                 let tx = {
6832                         let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6833                         // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
6834                         // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
6835                         // back to nodes[1] upon timeout otherwise.
6836                         assert_eq!(node_txn.len(), 1);
6837                         node_txn.remove(0)
6838                 };
6839
6840                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6841                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6842
6843                 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6844                 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
6845                 assert_eq!(events_4.len(), 1);
6846                 match events_4[0] {
6847                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6848                                 assert_eq!(flags & 0b10, 0b10);
6849                         },
6850                         _ => panic!("Unexpected event"),
6851                 }
6852
6853                 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
6854                 {
6855                         let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
6856                         monitors.get_mut(&OutPoint::new(Sha256dHash::from(&payment_event.commitment_msg.channel_id[..]), 0)).unwrap()
6857                                 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
6858                 }
6859                 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6860                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6861                 assert_eq!(node_txn.len(), 1);
6862                 assert_eq!(node_txn[0].input.len(), 1);
6863                 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
6864                 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
6865                 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
6866
6867                 check_spends!(node_txn[0], tx);
6868         }
6869
6870         #[test]
6871         fn test_unconf_chan() {
6872                 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
6873                 let nodes = create_network(2);
6874                 create_announced_chan_between_nodes(&nodes, 0, 1);
6875
6876                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6877                 assert_eq!(channel_state.by_id.len(), 1);
6878                 assert_eq!(channel_state.short_to_id.len(), 1);
6879                 mem::drop(channel_state);
6880
6881                 let mut headers = Vec::new();
6882                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6883                 headers.push(header.clone());
6884                 for _i in 2..100 {
6885                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6886                         headers.push(header.clone());
6887                 }
6888                 while !headers.is_empty() {
6889                         nodes[0].node.block_disconnected(&headers.pop().unwrap());
6890                 }
6891                 {
6892                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6893                         assert_eq!(events.len(), 1);
6894                         match events[0] {
6895                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6896                                         assert_eq!(flags & 0b10, 0b10);
6897                                 },
6898                                 _ => panic!("Unexpected event"),
6899                         }
6900                 }
6901                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6902                 assert_eq!(channel_state.by_id.len(), 0);
6903                 assert_eq!(channel_state.short_to_id.len(), 0);
6904         }
6905
6906         macro_rules! get_chan_reestablish_msgs {
6907                 ($src_node: expr, $dst_node: expr) => {
6908                         {
6909                                 let mut res = Vec::with_capacity(1);
6910                                 for msg in $src_node.node.get_and_clear_pending_msg_events() {
6911                                         if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
6912                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6913                                                 res.push(msg.clone());
6914                                         } else {
6915                                                 panic!("Unexpected event")
6916                                         }
6917                                 }
6918                                 res
6919                         }
6920                 }
6921         }
6922
6923         macro_rules! handle_chan_reestablish_msgs {
6924                 ($src_node: expr, $dst_node: expr) => {
6925                         {
6926                                 let msg_events = $src_node.node.get_and_clear_pending_msg_events();
6927                                 let mut idx = 0;
6928                                 let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
6929                                         idx += 1;
6930                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6931                                         Some(msg.clone())
6932                                 } else {
6933                                         None
6934                                 };
6935
6936                                 let mut revoke_and_ack = None;
6937                                 let mut commitment_update = None;
6938                                 let order = if let Some(ev) = msg_events.get(idx) {
6939                                         idx += 1;
6940                                         match ev {
6941                                                 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6942                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6943                                                         revoke_and_ack = Some(msg.clone());
6944                                                         RAACommitmentOrder::RevokeAndACKFirst
6945                                                 },
6946                                                 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6947                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6948                                                         commitment_update = Some(updates.clone());
6949                                                         RAACommitmentOrder::CommitmentFirst
6950                                                 },
6951                                                 _ => panic!("Unexpected event"),
6952                                         }
6953                                 } else {
6954                                         RAACommitmentOrder::CommitmentFirst
6955                                 };
6956
6957                                 if let Some(ev) = msg_events.get(idx) {
6958                                         match ev {
6959                                                 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6960                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6961                                                         assert!(revoke_and_ack.is_none());
6962                                                         revoke_and_ack = Some(msg.clone());
6963                                                 },
6964                                                 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6965                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6966                                                         assert!(commitment_update.is_none());
6967                                                         commitment_update = Some(updates.clone());
6968                                                 },
6969                                                 _ => panic!("Unexpected event"),
6970                                         }
6971                                 }
6972
6973                                 (funding_locked, revoke_and_ack, commitment_update, order)
6974                         }
6975                 }
6976         }
6977
6978         /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
6979         /// for claims/fails they are separated out.
6980         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)) {
6981                 node_a.node.peer_connected(&node_b.node.get_our_node_id());
6982                 let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
6983                 node_b.node.peer_connected(&node_a.node.get_our_node_id());
6984                 let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
6985
6986                 if send_funding_locked.0 {
6987                         // If a expects a funding_locked, it better not think it has received a revoke_and_ack
6988                         // from b
6989                         for reestablish in reestablish_1.iter() {
6990                                 assert_eq!(reestablish.next_remote_commitment_number, 0);
6991                         }
6992                 }
6993                 if send_funding_locked.1 {
6994                         // If b expects a funding_locked, it better not think it has received a revoke_and_ack
6995                         // from a
6996                         for reestablish in reestablish_2.iter() {
6997                                 assert_eq!(reestablish.next_remote_commitment_number, 0);
6998                         }
6999                 }
7000                 if send_funding_locked.0 || send_funding_locked.1 {
7001                         // If we expect any funding_locked's, both sides better have set
7002                         // next_local_commitment_number to 1
7003                         for reestablish in reestablish_1.iter() {
7004                                 assert_eq!(reestablish.next_local_commitment_number, 1);
7005                         }
7006                         for reestablish in reestablish_2.iter() {
7007                                 assert_eq!(reestablish.next_local_commitment_number, 1);
7008                         }
7009                 }
7010
7011                 let mut resp_1 = Vec::new();
7012                 for msg in reestablish_1 {
7013                         node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg).unwrap();
7014                         resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
7015                 }
7016                 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
7017                         check_added_monitors!(node_b, 1);
7018                 } else {
7019                         check_added_monitors!(node_b, 0);
7020                 }
7021
7022                 let mut resp_2 = Vec::new();
7023                 for msg in reestablish_2 {
7024                         node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg).unwrap();
7025                         resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
7026                 }
7027                 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
7028                         check_added_monitors!(node_a, 1);
7029                 } else {
7030                         check_added_monitors!(node_a, 0);
7031                 }
7032
7033                 // We dont yet support both needing updates, as that would require a different commitment dance:
7034                 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
7035                         (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
7036
7037                 for chan_msgs in resp_1.drain(..) {
7038                         if send_funding_locked.0 {
7039                                 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
7040                                 let announcement_event = node_a.node.get_and_clear_pending_msg_events();
7041                                 if !announcement_event.is_empty() {
7042                                         assert_eq!(announcement_event.len(), 1);
7043                                         if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
7044                                                 //TODO: Test announcement_sigs re-sending
7045                                         } else { panic!("Unexpected event!"); }
7046                                 }
7047                         } else {
7048                                 assert!(chan_msgs.0.is_none());
7049                         }
7050                         if pending_raa.0 {
7051                                 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
7052                                 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
7053                                 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
7054                                 check_added_monitors!(node_a, 1);
7055                         } else {
7056                                 assert!(chan_msgs.1.is_none());
7057                         }
7058                         if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
7059                                 let commitment_update = chan_msgs.2.unwrap();
7060                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
7061                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
7062                                 } else {
7063                                         assert!(commitment_update.update_add_htlcs.is_empty());
7064                                 }
7065                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
7066                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
7067                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
7068                                 for update_add in commitment_update.update_add_htlcs {
7069                                         node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add).unwrap();
7070                                 }
7071                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
7072                                         node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill).unwrap();
7073                                 }
7074                                 for update_fail in commitment_update.update_fail_htlcs {
7075                                         node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail).unwrap();
7076                                 }
7077
7078                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
7079                                         commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
7080                                 } else {
7081                                         node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
7082                                         check_added_monitors!(node_a, 1);
7083                                         let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
7084                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
7085                                         node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7086                                         assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
7087                                         check_added_monitors!(node_b, 1);
7088                                 }
7089                         } else {
7090                                 assert!(chan_msgs.2.is_none());
7091                         }
7092                 }
7093
7094                 for chan_msgs in resp_2.drain(..) {
7095                         if send_funding_locked.1 {
7096                                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
7097                                 let announcement_event = node_b.node.get_and_clear_pending_msg_events();
7098                                 if !announcement_event.is_empty() {
7099                                         assert_eq!(announcement_event.len(), 1);
7100                                         if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
7101                                                 //TODO: Test announcement_sigs re-sending
7102                                         } else { panic!("Unexpected event!"); }
7103                                 }
7104                         } else {
7105                                 assert!(chan_msgs.0.is_none());
7106                         }
7107                         if pending_raa.1 {
7108                                 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
7109                                 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
7110                                 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
7111                                 check_added_monitors!(node_b, 1);
7112                         } else {
7113                                 assert!(chan_msgs.1.is_none());
7114                         }
7115                         if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
7116                                 let commitment_update = chan_msgs.2.unwrap();
7117                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
7118                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
7119                                 }
7120                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
7121                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
7122                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
7123                                 for update_add in commitment_update.update_add_htlcs {
7124                                         node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add).unwrap();
7125                                 }
7126                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
7127                                         node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill).unwrap();
7128                                 }
7129                                 for update_fail in commitment_update.update_fail_htlcs {
7130                                         node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail).unwrap();
7131                                 }
7132
7133                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
7134                                         commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
7135                                 } else {
7136                                         node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
7137                                         check_added_monitors!(node_b, 1);
7138                                         let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
7139                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
7140                                         node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7141                                         assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
7142                                         check_added_monitors!(node_a, 1);
7143                                 }
7144                         } else {
7145                                 assert!(chan_msgs.2.is_none());
7146                         }
7147                 }
7148         }
7149
7150         #[test]
7151         fn test_simple_peer_disconnect() {
7152                 // Test that we can reconnect when there are no lost messages
7153                 let nodes = create_network(3);
7154                 create_announced_chan_between_nodes(&nodes, 0, 1);
7155                 create_announced_chan_between_nodes(&nodes, 1, 2);
7156
7157                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7158                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7159                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7160
7161                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7162                 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7163                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
7164                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
7165
7166                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7167                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7168                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7169
7170                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7171                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7172                 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7173                 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7174
7175                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7176                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7177
7178                 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3);
7179                 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
7180
7181                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
7182                 {
7183                         let events = nodes[0].node.get_and_clear_pending_events();
7184                         assert_eq!(events.len(), 2);
7185                         match events[0] {
7186                                 Event::PaymentSent { payment_preimage } => {
7187                                         assert_eq!(payment_preimage, payment_preimage_3);
7188                                 },
7189                                 _ => panic!("Unexpected event"),
7190                         }
7191                         match events[1] {
7192                                 Event::PaymentFailed { payment_hash, rejected_by_dest } => {
7193                                         assert_eq!(payment_hash, payment_hash_5);
7194                                         assert!(rejected_by_dest);
7195                                 },
7196                                 _ => panic!("Unexpected event"),
7197                         }
7198                 }
7199
7200                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
7201                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
7202         }
7203
7204         fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
7205                 // Test that we can reconnect when in-flight HTLC updates get dropped
7206                 let mut nodes = create_network(2);
7207                 if messages_delivered == 0 {
7208                         create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
7209                         // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
7210                 } else {
7211                         create_announced_chan_between_nodes(&nodes, 0, 1);
7212                 }
7213
7214                 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();
7215                 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7216
7217                 let payment_event = {
7218                         nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
7219                         check_added_monitors!(nodes[0], 1);
7220
7221                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7222                         assert_eq!(events.len(), 1);
7223                         SendEvent::from_event(events.remove(0))
7224                 };
7225                 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
7226
7227                 if messages_delivered < 2 {
7228                         // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
7229                 } else {
7230                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7231                         if messages_delivered >= 3 {
7232                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7233                                 check_added_monitors!(nodes[1], 1);
7234                                 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7235
7236                                 if messages_delivered >= 4 {
7237                                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7238                                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7239                                         check_added_monitors!(nodes[0], 1);
7240
7241                                         if messages_delivered >= 5 {
7242                                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
7243                                                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7244                                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7245                                                 check_added_monitors!(nodes[0], 1);
7246
7247                                                 if messages_delivered >= 6 {
7248                                                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7249                                                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7250                                                         check_added_monitors!(nodes[1], 1);
7251                                                 }
7252                                         }
7253                                 }
7254                         }
7255                 }
7256
7257                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7258                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7259                 if messages_delivered < 3 {
7260                         // Even if the funding_locked messages get exchanged, as long as nothing further was
7261                         // received on either side, both sides will need to resend them.
7262                         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
7263                 } else if messages_delivered == 3 {
7264                         // nodes[0] still wants its RAA + commitment_signed
7265                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
7266                 } else if messages_delivered == 4 {
7267                         // nodes[0] still wants its commitment_signed
7268                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
7269                 } else if messages_delivered == 5 {
7270                         // nodes[1] still wants its final RAA
7271                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
7272                 } else if messages_delivered == 6 {
7273                         // Everything was delivered...
7274                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7275                 }
7276
7277                 let events_1 = nodes[1].node.get_and_clear_pending_events();
7278                 assert_eq!(events_1.len(), 1);
7279                 match events_1[0] {
7280                         Event::PendingHTLCsForwardable { .. } => { },
7281                         _ => panic!("Unexpected event"),
7282                 };
7283
7284                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7285                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7286                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7287
7288                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7289                 nodes[1].node.process_pending_htlc_forwards();
7290
7291                 let events_2 = nodes[1].node.get_and_clear_pending_events();
7292                 assert_eq!(events_2.len(), 1);
7293                 match events_2[0] {
7294                         Event::PaymentReceived { ref payment_hash, amt } => {
7295                                 assert_eq!(payment_hash_1, *payment_hash);
7296                                 assert_eq!(amt, 1000000);
7297                         },
7298                         _ => panic!("Unexpected event"),
7299                 }
7300
7301                 nodes[1].node.claim_funds(payment_preimage_1);
7302                 check_added_monitors!(nodes[1], 1);
7303
7304                 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
7305                 assert_eq!(events_3.len(), 1);
7306                 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
7307                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
7308                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7309                                 assert!(updates.update_add_htlcs.is_empty());
7310                                 assert!(updates.update_fail_htlcs.is_empty());
7311                                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
7312                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
7313                                 assert!(updates.update_fee.is_none());
7314                                 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
7315                         },
7316                         _ => panic!("Unexpected event"),
7317                 };
7318
7319                 if messages_delivered >= 1 {
7320                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc).unwrap();
7321
7322                         let events_4 = nodes[0].node.get_and_clear_pending_events();
7323                         assert_eq!(events_4.len(), 1);
7324                         match events_4[0] {
7325                                 Event::PaymentSent { ref payment_preimage } => {
7326                                         assert_eq!(payment_preimage_1, *payment_preimage);
7327                                 },
7328                                 _ => panic!("Unexpected event"),
7329                         }
7330
7331                         if messages_delivered >= 2 {
7332                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
7333                                 check_added_monitors!(nodes[0], 1);
7334                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7335
7336                                 if messages_delivered >= 3 {
7337                                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7338                                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7339                                         check_added_monitors!(nodes[1], 1);
7340
7341                                         if messages_delivered >= 4 {
7342                                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
7343                                                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7344                                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7345                                                 check_added_monitors!(nodes[1], 1);
7346
7347                                                 if messages_delivered >= 5 {
7348                                                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7349                                                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7350                                                         check_added_monitors!(nodes[0], 1);
7351                                                 }
7352                                         }
7353                                 }
7354                         }
7355                 }
7356
7357                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7358                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7359                 if messages_delivered < 2 {
7360                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
7361                         //TODO: Deduplicate PaymentSent events, then enable this if:
7362                         //if messages_delivered < 1 {
7363                                 let events_4 = nodes[0].node.get_and_clear_pending_events();
7364                                 assert_eq!(events_4.len(), 1);
7365                                 match events_4[0] {
7366                                         Event::PaymentSent { ref payment_preimage } => {
7367                                                 assert_eq!(payment_preimage_1, *payment_preimage);
7368                                         },
7369                                         _ => panic!("Unexpected event"),
7370                                 }
7371                         //}
7372                 } else if messages_delivered == 2 {
7373                         // nodes[0] still wants its RAA + commitment_signed
7374                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
7375                 } else if messages_delivered == 3 {
7376                         // nodes[0] still wants its commitment_signed
7377                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
7378                 } else if messages_delivered == 4 {
7379                         // nodes[1] still wants its final RAA
7380                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
7381                 } else if messages_delivered == 5 {
7382                         // Everything was delivered...
7383                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7384                 }
7385
7386                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7387                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7388                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7389
7390                 // Channel should still work fine...
7391                 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
7392                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7393         }
7394
7395         #[test]
7396         fn test_drop_messages_peer_disconnect_a() {
7397                 do_test_drop_messages_peer_disconnect(0);
7398                 do_test_drop_messages_peer_disconnect(1);
7399                 do_test_drop_messages_peer_disconnect(2);
7400                 do_test_drop_messages_peer_disconnect(3);
7401         }
7402
7403         #[test]
7404         fn test_drop_messages_peer_disconnect_b() {
7405                 do_test_drop_messages_peer_disconnect(4);
7406                 do_test_drop_messages_peer_disconnect(5);
7407                 do_test_drop_messages_peer_disconnect(6);
7408         }
7409
7410         #[test]
7411         fn test_funding_peer_disconnect() {
7412                 // Test that we can lock in our funding tx while disconnected
7413                 let nodes = create_network(2);
7414                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
7415
7416                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7417                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7418
7419                 confirm_transaction(&nodes[0].chain_monitor, &tx, tx.version);
7420                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7421                 assert_eq!(events_1.len(), 1);
7422                 match events_1[0] {
7423                         MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7424                                 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7425                         },
7426                         _ => panic!("Unexpected event"),
7427                 }
7428
7429                 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7430
7431                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7432                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7433
7434                 confirm_transaction(&nodes[1].chain_monitor, &tx, tx.version);
7435                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7436                 assert_eq!(events_2.len(), 2);
7437                 match events_2[0] {
7438                         MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7439                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7440                         },
7441                         _ => panic!("Unexpected event"),
7442                 }
7443                 match events_2[1] {
7444                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ } => {
7445                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7446                         },
7447                         _ => panic!("Unexpected event"),
7448                 }
7449
7450                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7451
7452                 // TODO: We shouldn't need to manually pass list_usable_chanels here once we support
7453                 // rebroadcasting announcement_signatures upon reconnect.
7454
7455                 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();
7456                 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
7457                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
7458         }
7459
7460         #[test]
7461         fn test_drop_messages_peer_disconnect_dual_htlc() {
7462                 // Test that we can handle reconnecting when both sides of a channel have pending
7463                 // commitment_updates when we disconnect.
7464                 let mut nodes = create_network(2);
7465                 create_announced_chan_between_nodes(&nodes, 0, 1);
7466
7467                 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7468
7469                 // Now try to send a second payment which will fail to send
7470                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7471                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7472
7473                 nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
7474                 check_added_monitors!(nodes[0], 1);
7475
7476                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7477                 assert_eq!(events_1.len(), 1);
7478                 match events_1[0] {
7479                         MessageSendEvent::UpdateHTLCs { .. } => {},
7480                         _ => panic!("Unexpected event"),
7481                 }
7482
7483                 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7484                 check_added_monitors!(nodes[1], 1);
7485
7486                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7487                 assert_eq!(events_2.len(), 1);
7488                 match events_2[0] {
7489                         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 } } => {
7490                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7491                                 assert!(update_add_htlcs.is_empty());
7492                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7493                                 assert!(update_fail_htlcs.is_empty());
7494                                 assert!(update_fail_malformed_htlcs.is_empty());
7495                                 assert!(update_fee.is_none());
7496
7497                                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7498                                 let events_3 = nodes[0].node.get_and_clear_pending_events();
7499                                 assert_eq!(events_3.len(), 1);
7500                                 match events_3[0] {
7501                                         Event::PaymentSent { ref payment_preimage } => {
7502                                                 assert_eq!(*payment_preimage, payment_preimage_1);
7503                                         },
7504                                         _ => panic!("Unexpected event"),
7505                                 }
7506
7507                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
7508                                 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7509                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7510                                 check_added_monitors!(nodes[0], 1);
7511                         },
7512                         _ => panic!("Unexpected event"),
7513                 }
7514
7515                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7516                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7517
7518                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7519                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7520                 assert_eq!(reestablish_1.len(), 1);
7521                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7522                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7523                 assert_eq!(reestablish_2.len(), 1);
7524
7525                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7526                 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7527                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7528                 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7529
7530                 assert!(as_resp.0.is_none());
7531                 assert!(bs_resp.0.is_none());
7532
7533                 assert!(bs_resp.1.is_none());
7534                 assert!(bs_resp.2.is_none());
7535
7536                 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7537
7538                 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
7539                 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
7540                 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7541                 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7542                 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
7543                 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();
7544                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7545                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7546                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7547                 check_added_monitors!(nodes[1], 1);
7548
7549                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap();
7550                 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7551                 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
7552                 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
7553                 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
7554                 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
7555                 assert!(bs_second_commitment_signed.update_fee.is_none());
7556                 check_added_monitors!(nodes[1], 1);
7557
7558                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7559                 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7560                 assert!(as_commitment_signed.update_add_htlcs.is_empty());
7561                 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
7562                 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
7563                 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
7564                 assert!(as_commitment_signed.update_fee.is_none());
7565                 check_added_monitors!(nodes[0], 1);
7566
7567                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
7568                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7569                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7570                 check_added_monitors!(nodes[0], 1);
7571
7572                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
7573                 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7574                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7575                 check_added_monitors!(nodes[1], 1);
7576
7577                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7578                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7579                 check_added_monitors!(nodes[1], 1);
7580
7581                 let events_4 = nodes[1].node.get_and_clear_pending_events();
7582                 assert_eq!(events_4.len(), 1);
7583                 match events_4[0] {
7584                         Event::PendingHTLCsForwardable { .. } => { },
7585                         _ => panic!("Unexpected event"),
7586                 };
7587
7588                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7589                 nodes[1].node.process_pending_htlc_forwards();
7590
7591                 let events_5 = nodes[1].node.get_and_clear_pending_events();
7592                 assert_eq!(events_5.len(), 1);
7593                 match events_5[0] {
7594                         Event::PaymentReceived { ref payment_hash, amt: _ } => {
7595                                 assert_eq!(payment_hash_2, *payment_hash);
7596                         },
7597                         _ => panic!("Unexpected event"),
7598                 }
7599
7600                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
7601                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7602                 check_added_monitors!(nodes[0], 1);
7603
7604                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7605         }
7606
7607         #[test]
7608         fn test_simple_monitor_permanent_update_fail() {
7609                 // Test that we handle a simple permanent monitor update failure
7610                 let mut nodes = create_network(2);
7611                 create_announced_chan_between_nodes(&nodes, 0, 1);
7612
7613                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7614                 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7615
7616                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7617                 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route, payment_hash_1) {} else { panic!(); }
7618                 check_added_monitors!(nodes[0], 1);
7619
7620                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7621                 assert_eq!(events_1.len(), 2);
7622                 match events_1[0] {
7623                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7624                         _ => panic!("Unexpected event"),
7625                 };
7626                 match events_1[1] {
7627                         MessageSendEvent::HandleError { node_id, .. } => assert_eq!(node_id, nodes[1].node.get_our_node_id()),
7628                         _ => panic!("Unexpected event"),
7629                 };
7630
7631                 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7632                 // PaymentFailed event
7633
7634                 assert_eq!(nodes[0].node.list_channels().len(), 0);
7635         }
7636
7637         fn do_test_simple_monitor_temporary_update_fail(disconnect: bool) {
7638                 // Test that we can recover from a simple temporary monitor update failure optionally with
7639                 // a disconnect in between
7640                 let mut nodes = create_network(2);
7641                 create_announced_chan_between_nodes(&nodes, 0, 1);
7642
7643                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7644                 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7645
7646                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7647                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_1) {} else { panic!(); }
7648                 check_added_monitors!(nodes[0], 1);
7649
7650                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7651                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7652                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7653
7654                 if disconnect {
7655                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7656                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7657                         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7658                 }
7659
7660                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7661                 nodes[0].node.test_restore_channel_monitor();
7662                 check_added_monitors!(nodes[0], 1);
7663
7664                 let mut events_2 = nodes[0].node.get_and_clear_pending_msg_events();
7665                 assert_eq!(events_2.len(), 1);
7666                 let payment_event = SendEvent::from_event(events_2.pop().unwrap());
7667                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7668                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7669                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7670
7671                 expect_pending_htlcs_forwardable!(nodes[1]);
7672
7673                 let events_3 = nodes[1].node.get_and_clear_pending_events();
7674                 assert_eq!(events_3.len(), 1);
7675                 match events_3[0] {
7676                         Event::PaymentReceived { ref payment_hash, amt } => {
7677                                 assert_eq!(payment_hash_1, *payment_hash);
7678                                 assert_eq!(amt, 1000000);
7679                         },
7680                         _ => panic!("Unexpected event"),
7681                 }
7682
7683                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_1);
7684
7685                 // Now set it to failed again...
7686                 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7687                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7688                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route, payment_hash_2) {} else { panic!(); }
7689                 check_added_monitors!(nodes[0], 1);
7690
7691                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7692                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7693                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7694
7695                 if disconnect {
7696                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7697                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7698                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7699                 }
7700
7701                 // ...and make sure we can force-close a TemporaryFailure channel with a PermanentFailure
7702                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7703                 nodes[0].node.test_restore_channel_monitor();
7704                 check_added_monitors!(nodes[0], 1);
7705
7706                 let events_5 = nodes[0].node.get_and_clear_pending_msg_events();
7707                 assert_eq!(events_5.len(), 1);
7708                 match events_5[0] {
7709                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7710                         _ => panic!("Unexpected event"),
7711                 }
7712
7713                 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7714                 // PaymentFailed event
7715
7716                 assert_eq!(nodes[0].node.list_channels().len(), 0);
7717         }
7718
7719         #[test]
7720         fn test_simple_monitor_temporary_update_fail() {
7721                 do_test_simple_monitor_temporary_update_fail(false);
7722                 do_test_simple_monitor_temporary_update_fail(true);
7723         }
7724
7725         fn do_test_monitor_temporary_update_fail(disconnect_count: usize) {
7726                 let disconnect_flags = 8 | 16;
7727
7728                 // Test that we can recover from a temporary monitor update failure with some in-flight
7729                 // HTLCs going on at the same time potentially with some disconnection thrown in.
7730                 // * First we route a payment, then get a temporary monitor update failure when trying to
7731                 //   route a second payment. We then claim the first payment.
7732                 // * If disconnect_count is set, we will disconnect at this point (which is likely as
7733                 //   TemporaryFailure likely indicates net disconnect which resulted in failing to update
7734                 //   the ChannelMonitor on a watchtower).
7735                 // * If !(disconnect_count & 16) we deliver a update_fulfill_htlc/CS for the first payment
7736                 //   immediately, otherwise we wait sconnect and deliver them via the reconnect
7737                 //   channel_reestablish processing (ie disconnect_count & 16 makes no sense if
7738                 //   disconnect_count & !disconnect_flags is 0).
7739                 // * We then update the channel monitor, reconnecting if disconnect_count is set and walk
7740                 //   through message sending, potentially disconnect/reconnecting multiple times based on
7741                 //   disconnect_count, to get the update_fulfill_htlc through.
7742                 // * We then walk through more message exchanges to get the original update_add_htlc
7743                 //   through, swapping message ordering based on disconnect_count & 8 and optionally
7744                 //   disconnect/reconnecting based on disconnect_count.
7745                 let mut nodes = create_network(2);
7746                 create_announced_chan_between_nodes(&nodes, 0, 1);
7747
7748                 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7749
7750                 // Now try to send a second payment which will fail to send
7751                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7752                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7753
7754                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7755                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_2) {} else { panic!(); }
7756                 check_added_monitors!(nodes[0], 1);
7757
7758                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7759                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7760                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7761
7762                 // Claim the previous payment, which will result in a update_fulfill_htlc/CS from nodes[1]
7763                 // but nodes[0] won't respond since it is frozen.
7764                 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7765                 check_added_monitors!(nodes[1], 1);
7766                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7767                 assert_eq!(events_2.len(), 1);
7768                 let (bs_initial_fulfill, bs_initial_commitment_signed) = match events_2[0] {
7769                         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 } } => {
7770                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7771                                 assert!(update_add_htlcs.is_empty());
7772                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7773                                 assert!(update_fail_htlcs.is_empty());
7774                                 assert!(update_fail_malformed_htlcs.is_empty());
7775                                 assert!(update_fee.is_none());
7776
7777                                 if (disconnect_count & 16) == 0 {
7778                                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7779                                         let events_3 = nodes[0].node.get_and_clear_pending_events();
7780                                         assert_eq!(events_3.len(), 1);
7781                                         match events_3[0] {
7782                                                 Event::PaymentSent { ref payment_preimage } => {
7783                                                         assert_eq!(*payment_preimage, payment_preimage_1);
7784                                                 },
7785                                                 _ => panic!("Unexpected event"),
7786                                         }
7787
7788                                         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) {
7789                                                 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
7790                                         } else { panic!(); }
7791                                 }
7792
7793                                 (update_fulfill_htlcs[0].clone(), commitment_signed.clone())
7794                         },
7795                         _ => panic!("Unexpected event"),
7796                 };
7797
7798                 if disconnect_count & !disconnect_flags > 0 {
7799                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7800                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7801                 }
7802
7803                 // Now fix monitor updating...
7804                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7805                 nodes[0].node.test_restore_channel_monitor();
7806                 check_added_monitors!(nodes[0], 1);
7807
7808                 macro_rules! disconnect_reconnect_peers { () => { {
7809                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7810                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7811
7812                         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7813                         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7814                         assert_eq!(reestablish_1.len(), 1);
7815                         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7816                         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7817                         assert_eq!(reestablish_2.len(), 1);
7818
7819                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7820                         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7821                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7822                         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7823
7824                         assert!(as_resp.0.is_none());
7825                         assert!(bs_resp.0.is_none());
7826
7827                         (reestablish_1, reestablish_2, as_resp, bs_resp)
7828                 } } }
7829
7830                 let (payment_event, initial_revoke_and_ack) = if disconnect_count & !disconnect_flags > 0 {
7831                         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7832                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7833
7834                         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7835                         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7836                         assert_eq!(reestablish_1.len(), 1);
7837                         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7838                         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7839                         assert_eq!(reestablish_2.len(), 1);
7840
7841                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7842                         check_added_monitors!(nodes[0], 0);
7843                         let mut as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7844                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7845                         check_added_monitors!(nodes[1], 0);
7846                         let mut bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7847
7848                         assert!(as_resp.0.is_none());
7849                         assert!(bs_resp.0.is_none());
7850
7851                         assert!(bs_resp.1.is_none());
7852                         if (disconnect_count & 16) == 0 {
7853                                 assert!(bs_resp.2.is_none());
7854
7855                                 assert!(as_resp.1.is_some());
7856                                 assert!(as_resp.2.is_some());
7857                                 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7858                         } else {
7859                                 assert!(bs_resp.2.as_ref().unwrap().update_add_htlcs.is_empty());
7860                                 assert!(bs_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7861                                 assert!(bs_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7862                                 assert!(bs_resp.2.as_ref().unwrap().update_fee.is_none());
7863                                 assert!(bs_resp.2.as_ref().unwrap().update_fulfill_htlcs == vec![bs_initial_fulfill]);
7864                                 assert!(bs_resp.2.as_ref().unwrap().commitment_signed == bs_initial_commitment_signed);
7865
7866                                 assert!(as_resp.1.is_none());
7867
7868                                 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();
7869                                 let events_3 = nodes[0].node.get_and_clear_pending_events();
7870                                 assert_eq!(events_3.len(), 1);
7871                                 match events_3[0] {
7872                                         Event::PaymentSent { ref payment_preimage } => {
7873                                                 assert_eq!(*payment_preimage, payment_preimage_1);
7874                                         },
7875                                         _ => panic!("Unexpected event"),
7876                                 }
7877
7878                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7879                                 let as_resp_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7880                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7881                                 check_added_monitors!(nodes[0], 1);
7882
7883                                 as_resp.1 = Some(as_resp_raa);
7884                                 bs_resp.2 = None;
7885                         }
7886
7887                         if disconnect_count & !disconnect_flags > 1 {
7888                                 let (second_reestablish_1, second_reestablish_2, second_as_resp, second_bs_resp) = disconnect_reconnect_peers!();
7889
7890                                 if (disconnect_count & 16) == 0 {
7891                                         assert!(reestablish_1 == second_reestablish_1);
7892                                         assert!(reestablish_2 == second_reestablish_2);
7893                                 }
7894                                 assert!(as_resp == second_as_resp);
7895                                 assert!(bs_resp == second_bs_resp);
7896                         }
7897
7898                         (SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), as_resp.2.unwrap()), as_resp.1.unwrap())
7899                 } else {
7900                         let mut events_4 = nodes[0].node.get_and_clear_pending_msg_events();
7901                         assert_eq!(events_4.len(), 2);
7902                         (SendEvent::from_event(events_4.remove(0)), match events_4[0] {
7903                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
7904                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7905                                         msg.clone()
7906                                 },
7907                                 _ => panic!("Unexpected event"),
7908                         })
7909                 };
7910
7911                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7912
7913                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7914                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7915                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7916                 // nodes[1] is awaiting an RAA from nodes[0] still so get_event_msg's assert(len == 1) passes
7917                 check_added_monitors!(nodes[1], 1);
7918
7919                 if disconnect_count & !disconnect_flags > 2 {
7920                         let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7921
7922                         assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7923                         assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7924
7925                         assert!(as_resp.2.is_none());
7926                         assert!(bs_resp.2.is_none());
7927                 }
7928
7929                 let as_commitment_update;
7930                 let bs_second_commitment_update;
7931
7932                 macro_rules! handle_bs_raa { () => {
7933                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7934                         as_commitment_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7935                         assert!(as_commitment_update.update_add_htlcs.is_empty());
7936                         assert!(as_commitment_update.update_fulfill_htlcs.is_empty());
7937                         assert!(as_commitment_update.update_fail_htlcs.is_empty());
7938                         assert!(as_commitment_update.update_fail_malformed_htlcs.is_empty());
7939                         assert!(as_commitment_update.update_fee.is_none());
7940                         check_added_monitors!(nodes[0], 1);
7941                 } }
7942
7943                 macro_rules! handle_initial_raa { () => {
7944                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &initial_revoke_and_ack).unwrap();
7945                         bs_second_commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7946                         assert!(bs_second_commitment_update.update_add_htlcs.is_empty());
7947                         assert!(bs_second_commitment_update.update_fulfill_htlcs.is_empty());
7948                         assert!(bs_second_commitment_update.update_fail_htlcs.is_empty());
7949                         assert!(bs_second_commitment_update.update_fail_malformed_htlcs.is_empty());
7950                         assert!(bs_second_commitment_update.update_fee.is_none());
7951                         check_added_monitors!(nodes[1], 1);
7952                 } }
7953
7954                 if (disconnect_count & 8) == 0 {
7955                         handle_bs_raa!();
7956
7957                         if disconnect_count & !disconnect_flags > 3 {
7958                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7959
7960                                 assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7961                                 assert!(bs_resp.1.is_none());
7962
7963                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7964                                 assert!(bs_resp.2.is_none());
7965
7966                                 assert!(as_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7967                         }
7968
7969                         handle_initial_raa!();
7970
7971                         if disconnect_count & !disconnect_flags > 4 {
7972                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7973
7974                                 assert!(as_resp.1.is_none());
7975                                 assert!(bs_resp.1.is_none());
7976
7977                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7978                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7979                         }
7980                 } else {
7981                         handle_initial_raa!();
7982
7983                         if disconnect_count & !disconnect_flags > 3 {
7984                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7985
7986                                 assert!(as_resp.1.is_none());
7987                                 assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7988
7989                                 assert!(as_resp.2.is_none());
7990                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7991
7992                                 assert!(bs_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7993                         }
7994
7995                         handle_bs_raa!();
7996
7997                         if disconnect_count & !disconnect_flags > 4 {
7998                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7999
8000                                 assert!(as_resp.1.is_none());
8001                                 assert!(bs_resp.1.is_none());
8002
8003                                 assert!(as_resp.2.unwrap() == as_commitment_update);
8004                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
8005                         }
8006                 }
8007
8008                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_update.commitment_signed).unwrap();
8009                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8010                 // No commitment_signed so get_event_msg's assert(len == 1) passes
8011                 check_added_monitors!(nodes[0], 1);
8012
8013                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_update.commitment_signed).unwrap();
8014                 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
8015                 // No commitment_signed so get_event_msg's assert(len == 1) passes
8016                 check_added_monitors!(nodes[1], 1);
8017
8018                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
8019                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8020                 check_added_monitors!(nodes[1], 1);
8021
8022                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
8023                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8024                 check_added_monitors!(nodes[0], 1);
8025
8026                 expect_pending_htlcs_forwardable!(nodes[1]);
8027
8028                 let events_5 = nodes[1].node.get_and_clear_pending_events();
8029                 assert_eq!(events_5.len(), 1);
8030                 match events_5[0] {
8031                         Event::PaymentReceived { ref payment_hash, amt } => {
8032                                 assert_eq!(payment_hash_2, *payment_hash);
8033                                 assert_eq!(amt, 1000000);
8034                         },
8035                         _ => panic!("Unexpected event"),
8036                 }
8037
8038                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
8039         }
8040
8041         #[test]
8042         fn test_monitor_temporary_update_fail_a() {
8043                 do_test_monitor_temporary_update_fail(0);
8044                 do_test_monitor_temporary_update_fail(1);
8045                 do_test_monitor_temporary_update_fail(2);
8046                 do_test_monitor_temporary_update_fail(3);
8047                 do_test_monitor_temporary_update_fail(4);
8048                 do_test_monitor_temporary_update_fail(5);
8049         }
8050
8051         #[test]
8052         fn test_monitor_temporary_update_fail_b() {
8053                 do_test_monitor_temporary_update_fail(2 | 8);
8054                 do_test_monitor_temporary_update_fail(3 | 8);
8055                 do_test_monitor_temporary_update_fail(4 | 8);
8056                 do_test_monitor_temporary_update_fail(5 | 8);
8057         }
8058
8059         #[test]
8060         fn test_monitor_temporary_update_fail_c() {
8061                 do_test_monitor_temporary_update_fail(1 | 16);
8062                 do_test_monitor_temporary_update_fail(2 | 16);
8063                 do_test_monitor_temporary_update_fail(3 | 16);
8064                 do_test_monitor_temporary_update_fail(2 | 8 | 16);
8065                 do_test_monitor_temporary_update_fail(3 | 8 | 16);
8066         }
8067
8068         #[test]
8069         fn test_monitor_update_fail_cs() {
8070                 // Tests handling of a monitor update failure when processing an incoming commitment_signed
8071                 let mut nodes = create_network(2);
8072                 create_announced_chan_between_nodes(&nodes, 0, 1);
8073
8074                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8075                 let (payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
8076                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
8077                 check_added_monitors!(nodes[0], 1);
8078
8079                 let send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8080                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8081
8082                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8083                 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() {
8084                         assert_eq!(err, "Failed to update ChannelMonitor");
8085                 } else { panic!(); }
8086                 check_added_monitors!(nodes[1], 1);
8087                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8088
8089                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8090                 nodes[1].node.test_restore_channel_monitor();
8091                 check_added_monitors!(nodes[1], 1);
8092                 let responses = nodes[1].node.get_and_clear_pending_msg_events();
8093                 assert_eq!(responses.len(), 2);
8094
8095                 match responses[0] {
8096                         MessageSendEvent::SendRevokeAndACK { ref msg, ref node_id } => {
8097                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8098                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &msg).unwrap();
8099                                 check_added_monitors!(nodes[0], 1);
8100                         },
8101                         _ => panic!("Unexpected event"),
8102                 }
8103                 match responses[1] {
8104                         MessageSendEvent::UpdateHTLCs { ref updates, ref node_id } => {
8105                                 assert!(updates.update_add_htlcs.is_empty());
8106                                 assert!(updates.update_fulfill_htlcs.is_empty());
8107                                 assert!(updates.update_fail_htlcs.is_empty());
8108                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8109                                 assert!(updates.update_fee.is_none());
8110                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8111
8112                                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8113                                 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() {
8114                                         assert_eq!(err, "Failed to update ChannelMonitor");
8115                                 } else { panic!(); }
8116                                 check_added_monitors!(nodes[0], 1);
8117                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8118                         },
8119                         _ => panic!("Unexpected event"),
8120                 }
8121
8122                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
8123                 nodes[0].node.test_restore_channel_monitor();
8124                 check_added_monitors!(nodes[0], 1);
8125
8126                 let final_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8127                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &final_raa).unwrap();
8128                 check_added_monitors!(nodes[1], 1);
8129
8130                 let mut events = nodes[1].node.get_and_clear_pending_events();
8131                 assert_eq!(events.len(), 1);
8132                 match events[0] {
8133                         Event::PendingHTLCsForwardable { .. } => { },
8134                         _ => panic!("Unexpected event"),
8135                 };
8136                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8137                 nodes[1].node.process_pending_htlc_forwards();
8138
8139                 events = nodes[1].node.get_and_clear_pending_events();
8140                 assert_eq!(events.len(), 1);
8141                 match events[0] {
8142                         Event::PaymentReceived { payment_hash, amt } => {
8143                                 assert_eq!(payment_hash, our_payment_hash);
8144                                 assert_eq!(amt, 1000000);
8145                         },
8146                         _ => panic!("Unexpected event"),
8147                 };
8148
8149                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
8150         }
8151
8152         fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) {
8153                 // Tests handling of a monitor update failure when processing an incoming RAA
8154                 let mut nodes = create_network(3);
8155                 create_announced_chan_between_nodes(&nodes, 0, 1);
8156                 create_announced_chan_between_nodes(&nodes, 1, 2);
8157
8158                 // Rebalance a bit so that we can send backwards from 2 to 1.
8159                 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 5000000);
8160
8161                 // Route a first payment that we'll fail backwards
8162                 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
8163
8164                 // Fail the payment backwards, failing the monitor update on nodes[1]'s receipt of the RAA
8165                 assert!(nodes[2].node.fail_htlc_backwards(&payment_hash_1, PaymentFailReason::PreimageUnknown));
8166                 check_added_monitors!(nodes[2], 1);
8167
8168                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8169                 assert!(updates.update_add_htlcs.is_empty());
8170                 assert!(updates.update_fulfill_htlcs.is_empty());
8171                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8172                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8173                 assert!(updates.update_fee.is_none());
8174                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
8175
8176                 let bs_revoke_and_ack = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
8177                 check_added_monitors!(nodes[0], 0);
8178
8179                 // While the second channel is AwaitingRAA, forward a second payment to get it into the
8180                 // holding cell.
8181                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
8182                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8183                 nodes[0].node.send_payment(route, payment_hash_2).unwrap();
8184                 check_added_monitors!(nodes[0], 1);
8185
8186                 let mut 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);
8189
8190                 let events_1 = nodes[1].node.get_and_clear_pending_events();
8191                 assert_eq!(events_1.len(), 1);
8192                 match events_1[0] {
8193                         Event::PendingHTLCsForwardable { .. } => { },
8194                         _ => panic!("Unexpected event"),
8195                 };
8196
8197                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8198                 nodes[1].node.process_pending_htlc_forwards();
8199                 check_added_monitors!(nodes[1], 0);
8200                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8201
8202                 // Now fail monitor updating.
8203                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8204                 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() {
8205                         assert_eq!(err, "Failed to update ChannelMonitor");
8206                 } else { panic!(); }
8207                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8208                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8209                 check_added_monitors!(nodes[1], 1);
8210
8211                 // Attempt to forward a third payment but fail due to the second channel being unavailable
8212                 // for forwarding.
8213
8214                 let (_, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
8215                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8216                 nodes[0].node.send_payment(route, payment_hash_3).unwrap();
8217                 check_added_monitors!(nodes[0], 1);
8218
8219                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(()); // We succeed in updating the monitor for the first channel
8220                 send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8221                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8222                 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
8223                 check_added_monitors!(nodes[1], 0);
8224
8225                 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8226                 assert_eq!(events_2.len(), 1);
8227                 match events_2.remove(0) {
8228                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
8229                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8230                                 assert!(updates.update_fulfill_htlcs.is_empty());
8231                                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8232                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8233                                 assert!(updates.update_add_htlcs.is_empty());
8234                                 assert!(updates.update_fee.is_none());
8235
8236                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
8237                                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
8238
8239                                 let events = nodes[0].node.get_and_clear_pending_events();
8240                                 assert_eq!(events.len(), 1);
8241                                 if let Event::PaymentFailed { payment_hash, rejected_by_dest } = events[0] {
8242                                         assert_eq!(payment_hash, payment_hash_3);
8243                                         assert!(!rejected_by_dest);
8244                                 } else { panic!("Unexpected event!"); }
8245                         },
8246                         _ => panic!("Unexpected event type!"),
8247                 };
8248
8249                 let (payment_preimage_4, payment_hash_4) = if test_ignore_second_cs {
8250                         // Try to route another payment backwards from 2 to make sure 1 holds off on responding
8251                         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[0]);
8252                         let route = nodes[2].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8253                         nodes[2].node.send_payment(route, payment_hash_4).unwrap();
8254                         check_added_monitors!(nodes[2], 1);
8255
8256                         send_event = SendEvent::from_event(nodes[2].node.get_and_clear_pending_msg_events().remove(0));
8257                         nodes[1].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8258                         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) {
8259                                 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
8260                         } else { panic!(); }
8261                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8262                         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8263                         (Some(payment_preimage_4), Some(payment_hash_4))
8264                 } else { (None, None) };
8265
8266                 // Restore monitor updating, ensuring we immediately get a fail-back update and a
8267                 // update_add update.
8268                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8269                 nodes[1].node.test_restore_channel_monitor();
8270                 check_added_monitors!(nodes[1], 2);
8271
8272                 let mut events_3 = nodes[1].node.get_and_clear_pending_msg_events();
8273                 if test_ignore_second_cs {
8274                         assert_eq!(events_3.len(), 3);
8275                 } else {
8276                         assert_eq!(events_3.len(), 2);
8277                 }
8278
8279                 // Note that the ordering of the events for different nodes is non-prescriptive, though the
8280                 // ordering of the two events that both go to nodes[2] have to stay in the same order.
8281                 let messages_a = match events_3.pop().unwrap() {
8282                         MessageSendEvent::UpdateHTLCs { node_id, mut updates } => {
8283                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8284                                 assert!(updates.update_fulfill_htlcs.is_empty());
8285                                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8286                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8287                                 assert!(updates.update_add_htlcs.is_empty());
8288                                 assert!(updates.update_fee.is_none());
8289                                 (updates.update_fail_htlcs.remove(0), updates.commitment_signed)
8290                         },
8291                         _ => panic!("Unexpected event type!"),
8292                 };
8293                 let raa = if test_ignore_second_cs {
8294                         match events_3.remove(1) {
8295                                 MessageSendEvent::SendRevokeAndACK { node_id, msg } => {
8296                                         assert_eq!(node_id, nodes[2].node.get_our_node_id());
8297                                         Some(msg.clone())
8298                                 },
8299                                 _ => panic!("Unexpected event"),
8300                         }
8301                 } else { None };
8302                 let send_event_b = SendEvent::from_event(events_3.remove(0));
8303                 assert_eq!(send_event_b.node_id, nodes[2].node.get_our_node_id());
8304
8305                 // Now deliver the new messages...
8306
8307                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &messages_a.0).unwrap();
8308                 commitment_signed_dance!(nodes[0], nodes[1], messages_a.1, false);
8309                 let events_4 = nodes[0].node.get_and_clear_pending_events();
8310                 assert_eq!(events_4.len(), 1);
8311                 if let Event::PaymentFailed { payment_hash, rejected_by_dest } = events_4[0] {
8312                         assert_eq!(payment_hash, payment_hash_1);
8313                         assert!(rejected_by_dest);
8314                 } else { panic!("Unexpected event!"); }
8315
8316                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event_b.msgs[0]).unwrap();
8317                 if test_ignore_second_cs {
8318                         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event_b.commitment_msg).unwrap();
8319                         check_added_monitors!(nodes[2], 1);
8320                         let bs_revoke_and_ack = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8321                         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa.unwrap()).unwrap();
8322                         check_added_monitors!(nodes[2], 1);
8323                         let bs_cs = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8324                         assert!(bs_cs.update_add_htlcs.is_empty());
8325                         assert!(bs_cs.update_fail_htlcs.is_empty());
8326                         assert!(bs_cs.update_fail_malformed_htlcs.is_empty());
8327                         assert!(bs_cs.update_fulfill_htlcs.is_empty());
8328                         assert!(bs_cs.update_fee.is_none());
8329
8330                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
8331                         check_added_monitors!(nodes[1], 1);
8332                         let as_cs = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
8333                         assert!(as_cs.update_add_htlcs.is_empty());
8334                         assert!(as_cs.update_fail_htlcs.is_empty());
8335                         assert!(as_cs.update_fail_malformed_htlcs.is_empty());
8336                         assert!(as_cs.update_fulfill_htlcs.is_empty());
8337                         assert!(as_cs.update_fee.is_none());
8338
8339                         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_cs.commitment_signed).unwrap();
8340                         check_added_monitors!(nodes[1], 1);
8341                         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
8342
8343                         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_cs.commitment_signed).unwrap();
8344                         check_added_monitors!(nodes[2], 1);
8345                         let bs_second_raa = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8346
8347                         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
8348                         check_added_monitors!(nodes[2], 1);
8349                         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
8350
8351                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_second_raa).unwrap();
8352                         check_added_monitors!(nodes[1], 1);
8353                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8354                 } else {
8355                         commitment_signed_dance!(nodes[2], nodes[1], send_event_b.commitment_msg, false);
8356                 }
8357
8358                 let events_5 = nodes[2].node.get_and_clear_pending_events();
8359                 assert_eq!(events_5.len(), 1);
8360                 match events_5[0] {
8361                         Event::PendingHTLCsForwardable { .. } => { },
8362                         _ => panic!("Unexpected event"),
8363                 };
8364
8365                 nodes[2].node.channel_state.lock().unwrap().next_forward = Instant::now();
8366                 nodes[2].node.process_pending_htlc_forwards();
8367
8368                 let events_6 = nodes[2].node.get_and_clear_pending_events();
8369                 assert_eq!(events_6.len(), 1);
8370                 match events_6[0] {
8371                         Event::PaymentReceived { payment_hash, .. } => { assert_eq!(payment_hash, payment_hash_2); },
8372                         _ => panic!("Unexpected event"),
8373                 };
8374
8375                 if test_ignore_second_cs {
8376                         let events_7 = nodes[1].node.get_and_clear_pending_events();
8377                         assert_eq!(events_7.len(), 1);
8378                         match events_7[0] {
8379                                 Event::PendingHTLCsForwardable { .. } => { },
8380                                 _ => panic!("Unexpected event"),
8381                         };
8382
8383                         nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8384                         nodes[1].node.process_pending_htlc_forwards();
8385                         check_added_monitors!(nodes[1], 1);
8386
8387                         send_event = SendEvent::from_node(&nodes[1]);
8388                         assert_eq!(send_event.node_id, nodes[0].node.get_our_node_id());
8389                         assert_eq!(send_event.msgs.len(), 1);
8390                         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8391                         commitment_signed_dance!(nodes[0], nodes[1], send_event.commitment_msg, false);
8392
8393                         let events_8 = nodes[0].node.get_and_clear_pending_events();
8394                         assert_eq!(events_8.len(), 1);
8395                         match events_8[0] {
8396                                 Event::PendingHTLCsForwardable { .. } => { },
8397                                 _ => panic!("Unexpected event"),
8398                         };
8399
8400                         nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
8401                         nodes[0].node.process_pending_htlc_forwards();
8402
8403                         let events_9 = nodes[0].node.get_and_clear_pending_events();
8404                         assert_eq!(events_9.len(), 1);
8405                         match events_9[0] {
8406                                 Event::PaymentReceived { payment_hash, .. } => assert_eq!(payment_hash, payment_hash_4.unwrap()),
8407                                 _ => panic!("Unexpected event"),
8408                         };
8409                         claim_payment(&nodes[2], &[&nodes[1], &nodes[0]], payment_preimage_4.unwrap());
8410                 }
8411
8412                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
8413         }
8414
8415         #[test]
8416         fn test_monitor_update_fail_raa() {
8417                 do_test_monitor_update_fail_raa(false);
8418                 do_test_monitor_update_fail_raa(true);
8419         }
8420
8421         #[test]
8422         fn test_monitor_update_fail_reestablish() {
8423                 // Simple test for message retransmission after monitor update failure on
8424                 // channel_reestablish generating a monitor update (which comes from freeing holding cell
8425                 // HTLCs).
8426                 let mut nodes = create_network(3);
8427                 create_announced_chan_between_nodes(&nodes, 0, 1);
8428                 create_announced_chan_between_nodes(&nodes, 1, 2);
8429
8430                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
8431
8432                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8433                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8434
8435                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
8436                 check_added_monitors!(nodes[2], 1);
8437                 let mut updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8438                 assert!(updates.update_add_htlcs.is_empty());
8439                 assert!(updates.update_fail_htlcs.is_empty());
8440                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8441                 assert!(updates.update_fee.is_none());
8442                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8443                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8444                 check_added_monitors!(nodes[1], 1);
8445                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8446                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
8447
8448                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8449                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8450                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8451
8452                 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
8453                 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8454
8455                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
8456
8457                 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() {
8458                         assert_eq!(err, "Failed to update ChannelMonitor");
8459                 } else { panic!(); }
8460                 check_added_monitors!(nodes[1], 1);
8461
8462                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8463                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8464
8465                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8466                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8467
8468                 assert!(as_reestablish == get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()));
8469                 assert!(bs_reestablish == get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id()));
8470
8471                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
8472
8473                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish).unwrap();
8474                 check_added_monitors!(nodes[1], 0);
8475                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8476
8477                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8478                 nodes[1].node.test_restore_channel_monitor();
8479                 check_added_monitors!(nodes[1], 1);
8480
8481                 updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8482                 assert!(updates.update_add_htlcs.is_empty());
8483                 assert!(updates.update_fail_htlcs.is_empty());
8484                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8485                 assert!(updates.update_fee.is_none());
8486                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8487                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8488                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
8489
8490                 let events = nodes[0].node.get_and_clear_pending_events();
8491                 assert_eq!(events.len(), 1);
8492                 match events[0] {
8493                         Event::PaymentSent { payment_preimage, .. } => assert_eq!(payment_preimage, our_payment_preimage),
8494                         _ => panic!("Unexpected event"),
8495                 }
8496         }
8497
8498         #[test]
8499         fn test_invalid_channel_announcement() {
8500                 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
8501                 let secp_ctx = Secp256k1::new();
8502                 let nodes = create_network(2);
8503
8504                 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1]);
8505
8506                 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8507                 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
8508                 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
8509                 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
8510
8511                 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 } );
8512
8513                 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
8514                 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
8515
8516                 let as_network_key = nodes[0].node.get_our_node_id();
8517                 let bs_network_key = nodes[1].node.get_our_node_id();
8518
8519                 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
8520
8521                 let mut chan_announcement;
8522
8523                 macro_rules! dummy_unsigned_msg {
8524                         () => {
8525                                 msgs::UnsignedChannelAnnouncement {
8526                                         features: msgs::GlobalFeatures::new(),
8527                                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
8528                                         short_channel_id: as_chan.get_short_channel_id().unwrap(),
8529                                         node_id_1: if were_node_one { as_network_key } else { bs_network_key },
8530                                         node_id_2: if were_node_one { bs_network_key } else { as_network_key },
8531                                         bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
8532                                         bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
8533                                         excess_data: Vec::new(),
8534                                 };
8535                         }
8536                 }
8537
8538                 macro_rules! sign_msg {
8539                         ($unsigned_msg: expr) => {
8540                                 let msghash = Message::from_slice(&Sha256dHash::from_data(&$unsigned_msg.encode()[..])[..]).unwrap();
8541                                 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
8542                                 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
8543                                 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].node.our_network_key);
8544                                 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].node.our_network_key);
8545                                 chan_announcement = msgs::ChannelAnnouncement {
8546                                         node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
8547                                         node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
8548                                         bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
8549                                         bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
8550                                         contents: $unsigned_msg
8551                                 }
8552                         }
8553                 }
8554
8555                 let unsigned_msg = dummy_unsigned_msg!();
8556                 sign_msg!(unsigned_msg);
8557                 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
8558                 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 } );
8559
8560                 // Configured with Network::Testnet
8561                 let mut unsigned_msg = dummy_unsigned_msg!();
8562                 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
8563                 sign_msg!(unsigned_msg);
8564                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
8565
8566                 let mut unsigned_msg = dummy_unsigned_msg!();
8567                 unsigned_msg.chain_hash = Sha256dHash::from_data(&[1,2,3,4,5,6,7,8,9]);
8568                 sign_msg!(unsigned_msg);
8569                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
8570         }
8571
8572         struct VecWriter(Vec<u8>);
8573         impl Writer for VecWriter {
8574                 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
8575                         self.0.extend_from_slice(buf);
8576                         Ok(())
8577                 }
8578                 fn size_hint(&mut self, size: usize) {
8579                         self.0.reserve_exact(size);
8580                 }
8581         }
8582
8583         #[test]
8584         fn test_no_txn_manager_serialize_deserialize() {
8585                 let mut nodes = create_network(2);
8586
8587                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
8588
8589                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8590
8591                 let nodes_0_serialized = nodes[0].node.encode();
8592                 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8593                 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8594
8595                 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())));
8596                 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8597                 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8598                 assert!(chan_0_monitor_read.is_empty());
8599
8600                 let mut nodes_0_read = &nodes_0_serialized[..];
8601                 let config = UserConfig::new();
8602                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8603                 let (_, nodes_0_deserialized) = {
8604                         let mut channel_monitors = HashMap::new();
8605                         channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8606                         <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8607                                 default_config: config,
8608                                 keys_manager,
8609                                 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8610                                 monitor: nodes[0].chan_monitor.clone(),
8611                                 chain_monitor: nodes[0].chain_monitor.clone(),
8612                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8613                                 logger: Arc::new(test_utils::TestLogger::new()),
8614                                 channel_monitors: &channel_monitors,
8615                         }).unwrap()
8616                 };
8617                 assert!(nodes_0_read.is_empty());
8618
8619                 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8620                 nodes[0].node = Arc::new(nodes_0_deserialized);
8621                 let nodes_0_as_listener: Arc<ChainListener> = nodes[0].node.clone();
8622                 nodes[0].chain_monitor.register_listener(Arc::downgrade(&nodes_0_as_listener));
8623                 assert_eq!(nodes[0].node.list_channels().len(), 1);
8624                 check_added_monitors!(nodes[0], 1);
8625
8626                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8627                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
8628                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8629                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
8630
8631                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
8632                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8633                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
8634                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8635
8636                 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8637                 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8638                 for node in nodes.iter() {
8639                         assert!(node.router.handle_channel_announcement(&announcement).unwrap());
8640                         node.router.handle_channel_update(&as_update).unwrap();
8641                         node.router.handle_channel_update(&bs_update).unwrap();
8642                 }
8643
8644                 send_payment(&nodes[0], &[&nodes[1]], 1000000);
8645         }
8646
8647         #[test]
8648         fn test_simple_manager_serialize_deserialize() {
8649                 let mut nodes = create_network(2);
8650                 create_announced_chan_between_nodes(&nodes, 0, 1);
8651
8652                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8653                 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8654
8655                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8656
8657                 let nodes_0_serialized = nodes[0].node.encode();
8658                 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8659                 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8660
8661                 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())));
8662                 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8663                 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8664                 assert!(chan_0_monitor_read.is_empty());
8665
8666                 let mut nodes_0_read = &nodes_0_serialized[..];
8667                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8668                 let (_, nodes_0_deserialized) = {
8669                         let mut channel_monitors = HashMap::new();
8670                         channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8671                         <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8672                                 default_config: UserConfig::new(),
8673                                 keys_manager,
8674                                 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8675                                 monitor: nodes[0].chan_monitor.clone(),
8676                                 chain_monitor: nodes[0].chain_monitor.clone(),
8677                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8678                                 logger: Arc::new(test_utils::TestLogger::new()),
8679                                 channel_monitors: &channel_monitors,
8680                         }).unwrap()
8681                 };
8682                 assert!(nodes_0_read.is_empty());
8683
8684                 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8685                 nodes[0].node = Arc::new(nodes_0_deserialized);
8686                 check_added_monitors!(nodes[0], 1);
8687
8688                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8689
8690                 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
8691                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
8692         }
8693
8694         #[test]
8695         fn test_manager_serialize_deserialize_inconsistent_monitor() {
8696                 // Test deserializing a ChannelManager with a out-of-date ChannelMonitor
8697                 let mut nodes = create_network(4);
8698                 create_announced_chan_between_nodes(&nodes, 0, 1);
8699                 create_announced_chan_between_nodes(&nodes, 2, 0);
8700                 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3);
8701
8702                 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
8703
8704                 // Serialize the ChannelManager here, but the monitor we keep up-to-date
8705                 let nodes_0_serialized = nodes[0].node.encode();
8706
8707                 route_payment(&nodes[0], &[&nodes[3]], 1000000);
8708                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8709                 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8710                 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8711
8712                 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
8713                 // nodes[3])
8714                 let mut node_0_monitors_serialized = Vec::new();
8715                 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
8716                         let mut writer = VecWriter(Vec::new());
8717                         monitor.1.write_for_disk(&mut writer).unwrap();
8718                         node_0_monitors_serialized.push(writer.0);
8719                 }
8720
8721                 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())));
8722                 let mut node_0_monitors = Vec::new();
8723                 for serialized in node_0_monitors_serialized.iter() {
8724                         let mut read = &serialized[..];
8725                         let (_, monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
8726                         assert!(read.is_empty());
8727                         node_0_monitors.push(monitor);
8728                 }
8729
8730                 let mut nodes_0_read = &nodes_0_serialized[..];
8731                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8732                 let (_, nodes_0_deserialized) = <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8733                         default_config: UserConfig::new(),
8734                         keys_manager,
8735                         fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8736                         monitor: nodes[0].chan_monitor.clone(),
8737                         chain_monitor: nodes[0].chain_monitor.clone(),
8738                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8739                         logger: Arc::new(test_utils::TestLogger::new()),
8740                         channel_monitors: &node_0_monitors.iter().map(|monitor| { (monitor.get_funding_txo().unwrap(), monitor) }).collect(),
8741                 }).unwrap();
8742                 assert!(nodes_0_read.is_empty());
8743
8744                 { // Channel close should result in a commitment tx and an HTLC tx
8745                         let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8746                         assert_eq!(txn.len(), 2);
8747                         assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
8748                         assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
8749                 }
8750
8751                 for monitor in node_0_monitors.drain(..) {
8752                         assert!(nodes[0].chan_monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor).is_ok());
8753                         check_added_monitors!(nodes[0], 1);
8754                 }
8755                 nodes[0].node = Arc::new(nodes_0_deserialized);
8756
8757                 // nodes[1] and nodes[2] have no lost state with nodes[0]...
8758                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8759                 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8760                 //... and we can even still claim the payment!
8761                 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
8762
8763                 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id());
8764                 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8765                 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id());
8766                 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) {
8767                         assert_eq!(msg.channel_id, channel_id);
8768                 } else { panic!("Unexpected result"); }
8769         }
8770
8771         macro_rules! check_spendable_outputs {
8772                 ($node: expr, $der_idx: expr) => {
8773                         {
8774                                 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
8775                                 let mut txn = Vec::new();
8776                                 for event in events {
8777                                         match event {
8778                                                 Event::SpendableOutputs { ref outputs } => {
8779                                                         for outp in outputs {
8780                                                                 match *outp {
8781                                                                         SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
8782                                                                                 let input = TxIn {
8783                                                                                         previous_output: outpoint.clone(),
8784                                                                                         script_sig: Script::new(),
8785                                                                                         sequence: 0,
8786                                                                                         witness: Vec::new(),
8787                                                                                 };
8788                                                                                 let outp = TxOut {
8789                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8790                                                                                         value: output.value,
8791                                                                                 };
8792                                                                                 let mut spend_tx = Transaction {
8793                                                                                         version: 2,
8794                                                                                         lock_time: 0,
8795                                                                                         input: vec![input],
8796                                                                                         output: vec![outp],
8797                                                                                 };
8798                                                                                 let secp_ctx = Secp256k1::new();
8799                                                                                 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
8800                                                                                 let witness_script = Address::p2pkh(&remotepubkey, Network::Testnet).script_pubkey();
8801                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8802                                                                                 let remotesig = secp_ctx.sign(&sighash, key);
8803                                                                                 spend_tx.input[0].witness.push(remotesig.serialize_der(&secp_ctx).to_vec());
8804                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8805                                                                                 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
8806                                                                                 txn.push(spend_tx);
8807                                                                         },
8808                                                                         SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
8809                                                                                 let input = TxIn {
8810                                                                                         previous_output: outpoint.clone(),
8811                                                                                         script_sig: Script::new(),
8812                                                                                         sequence: *to_self_delay as u32,
8813                                                                                         witness: Vec::new(),
8814                                                                                 };
8815                                                                                 let outp = TxOut {
8816                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8817                                                                                         value: output.value,
8818                                                                                 };
8819                                                                                 let mut spend_tx = Transaction {
8820                                                                                         version: 2,
8821                                                                                         lock_time: 0,
8822                                                                                         input: vec![input],
8823                                                                                         output: vec![outp],
8824                                                                                 };
8825                                                                                 let secp_ctx = Secp256k1::new();
8826                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
8827                                                                                 let local_delaysig = secp_ctx.sign(&sighash, key);
8828                                                                                 spend_tx.input[0].witness.push(local_delaysig.serialize_der(&secp_ctx).to_vec());
8829                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8830                                                                                 spend_tx.input[0].witness.push(vec!(0));
8831                                                                                 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
8832                                                                                 txn.push(spend_tx);
8833                                                                         },
8834                                                                         SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
8835                                                                                 let secp_ctx = Secp256k1::new();
8836                                                                                 let input = TxIn {
8837                                                                                         previous_output: outpoint.clone(),
8838                                                                                         script_sig: Script::new(),
8839                                                                                         sequence: 0,
8840                                                                                         witness: Vec::new(),
8841                                                                                 };
8842                                                                                 let outp = TxOut {
8843                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8844                                                                                         value: output.value,
8845                                                                                 };
8846                                                                                 let mut spend_tx = Transaction {
8847                                                                                         version: 2,
8848                                                                                         lock_time: 0,
8849                                                                                         input: vec![input],
8850                                                                                         output: vec![outp.clone()],
8851                                                                                 };
8852                                                                                 let secret = {
8853                                                                                         match ExtendedPrivKey::new_master(&secp_ctx, Network::Testnet, &$node.node_seed) {
8854                                                                                                 Ok(master_key) => {
8855                                                                                                         match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx)) {
8856                                                                                                                 Ok(key) => key,
8857                                                                                                                 Err(_) => panic!("Your RNG is busted"),
8858                                                                                                         }
8859                                                                                                 }
8860                                                                                                 Err(_) => panic!("Your rng is busted"),
8861                                                                                         }
8862                                                                                 };
8863                                                                                 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
8864                                                                                 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
8865                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8866                                                                                 let sig = secp_ctx.sign(&sighash, &secret.secret_key);
8867                                                                                 spend_tx.input[0].witness.push(sig.serialize_der(&secp_ctx).to_vec());
8868                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8869                                                                                 spend_tx.input[0].witness.push(pubkey.serialize().to_vec());
8870                                                                                 txn.push(spend_tx);
8871                                                                         },
8872                                                                 }
8873                                                         }
8874                                                 },
8875                                                 _ => panic!("Unexpected event"),
8876                                         };
8877                                 }
8878                                 txn
8879                         }
8880                 }
8881         }
8882
8883         #[test]
8884         fn test_claim_sizeable_push_msat() {
8885                 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
8886                 let nodes = create_network(2);
8887
8888                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8889                 nodes[1].node.force_close_channel(&chan.2);
8890                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8891                 match events[0] {
8892                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8893                         _ => panic!("Unexpected event"),
8894                 }
8895                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8896                 assert_eq!(node_txn.len(), 1);
8897                 check_spends!(node_txn[0], chan.3.clone());
8898                 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
8899
8900                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8901                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8902                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8903                 assert_eq!(spend_txn.len(), 1);
8904                 check_spends!(spend_txn[0], node_txn[0].clone());
8905         }
8906
8907         #[test]
8908         fn test_claim_on_remote_sizeable_push_msat() {
8909                 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8910                 // to_remote output is encumbered by a P2WPKH
8911
8912                 let nodes = create_network(2);
8913
8914                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8915                 nodes[0].node.force_close_channel(&chan.2);
8916                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8917                 match events[0] {
8918                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8919                         _ => panic!("Unexpected event"),
8920                 }
8921                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8922                 assert_eq!(node_txn.len(), 1);
8923                 check_spends!(node_txn[0], chan.3.clone());
8924                 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
8925
8926                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8927                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8928                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8929                 match events[0] {
8930                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8931                         _ => panic!("Unexpected event"),
8932                 }
8933                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8934                 assert_eq!(spend_txn.len(), 2);
8935                 assert_eq!(spend_txn[0], spend_txn[1]);
8936                 check_spends!(spend_txn[0], node_txn[0].clone());
8937         }
8938
8939         #[test]
8940         fn test_claim_on_remote_revoked_sizeable_push_msat() {
8941                 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8942                 // to_remote output is encumbered by a P2WPKH
8943
8944                 let nodes = create_network(2);
8945
8946                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
8947                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8948                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
8949                 assert_eq!(revoked_local_txn[0].input.len(), 1);
8950                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8951
8952                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8953                 let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8954                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
8955                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8956                 match events[0] {
8957                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8958                         _ => panic!("Unexpected event"),
8959                 }
8960                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8961                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8962                 assert_eq!(spend_txn.len(), 4);
8963                 assert_eq!(spend_txn[0], spend_txn[2]); // to_remote output on revoked remote commitment_tx
8964                 check_spends!(spend_txn[0], revoked_local_txn[0].clone());
8965                 assert_eq!(spend_txn[1], spend_txn[3]); // to_local output on local commitment tx
8966                 check_spends!(spend_txn[1], node_txn[0].clone());
8967         }
8968
8969         #[test]
8970         fn test_static_spendable_outputs_preimage_tx() {
8971                 let nodes = create_network(2);
8972
8973                 // Create some initial channels
8974                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8975
8976                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8977
8978                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8979                 assert_eq!(commitment_tx[0].input.len(), 1);
8980                 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
8981
8982                 // Settle A's commitment tx on B's chain
8983                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8984                 assert!(nodes[1].node.claim_funds(payment_preimage));
8985                 check_added_monitors!(nodes[1], 1);
8986                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
8987                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8988                 match events[0] {
8989                         MessageSendEvent::UpdateHTLCs { .. } => {},
8990                         _ => panic!("Unexpected event"),
8991                 }
8992                 match events[1] {
8993                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8994                         _ => panic!("Unexepected event"),
8995                 }
8996
8997                 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
8998                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 1 (local commitment tx), ChannelMonitor: 2 (1 preimage tx) * 2 (block-rescan)
8999                 check_spends!(node_txn[0], commitment_tx[0].clone());
9000                 assert_eq!(node_txn[0], node_txn[2]);
9001                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9002                 check_spends!(node_txn[1], chan_1.3.clone());
9003
9004                 let spend_txn = check_spendable_outputs!(nodes[1], 1); // , 0, 0, 1, 1);
9005                 assert_eq!(spend_txn.len(), 2);
9006                 assert_eq!(spend_txn[0], spend_txn[1]);
9007                 check_spends!(spend_txn[0], node_txn[0].clone());
9008         }
9009
9010         #[test]
9011         fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
9012                 let nodes = create_network(2);
9013
9014                 // Create some initial channels
9015                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9016
9017                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9018                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
9019                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9020                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9021
9022                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9023
9024                 let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9025                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9026                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9027                 match events[0] {
9028                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9029                         _ => panic!("Unexpected event"),
9030                 }
9031                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9032                 assert_eq!(node_txn.len(), 3);
9033                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]);
9034                 assert_eq!(node_txn[0].input.len(), 2);
9035                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
9036
9037                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9038                 assert_eq!(spend_txn.len(), 2);
9039                 assert_eq!(spend_txn[0], spend_txn[1]);
9040                 check_spends!(spend_txn[0], node_txn[0].clone());
9041         }
9042
9043         #[test]
9044         fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
9045                 let nodes = create_network(2);
9046
9047                 // Create some initial channels
9048                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9049
9050                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9051                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9052                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9053                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9054
9055                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9056
9057                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9058                 // A will generate HTLC-Timeout from revoked commitment tx
9059                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9060                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9061                 match events[0] {
9062                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9063                         _ => panic!("Unexpected event"),
9064                 }
9065                 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9066                 assert_eq!(revoked_htlc_txn.len(), 3);
9067                 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
9068                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
9069                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9070                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
9071                 check_spends!(revoked_htlc_txn[1], chan_1.3.clone());
9072
9073                 // B will generate justice tx from A's revoked commitment/HTLC tx
9074                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
9075                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9076                 match events[0] {
9077                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9078                         _ => panic!("Unexpected event"),
9079                 }
9080
9081                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9082                 assert_eq!(node_txn.len(), 4);
9083                 assert_eq!(node_txn[3].input.len(), 1);
9084                 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
9085
9086                 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
9087                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9088                 assert_eq!(spend_txn.len(), 3);
9089                 assert_eq!(spend_txn[0], spend_txn[1]);
9090                 check_spends!(spend_txn[0], node_txn[0].clone());
9091                 check_spends!(spend_txn[2], node_txn[3].clone());
9092         }
9093
9094         #[test]
9095         fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
9096                 let nodes = create_network(2);
9097
9098                 // Create some initial channels
9099                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9100
9101                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9102                 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9103                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9104                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9105
9106                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9107
9108                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9109                 // B will generate HTLC-Success from revoked commitment tx
9110                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9111                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9112                 match events[0] {
9113                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9114                         _ => panic!("Unexpected event"),
9115                 }
9116                 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9117
9118                 assert_eq!(revoked_htlc_txn.len(), 3);
9119                 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
9120                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
9121                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9122                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
9123
9124                 // A will generate justice tx from B's revoked commitment/HTLC tx
9125                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
9126                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9127                 match events[0] {
9128                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9129                         _ => panic!("Unexpected event"),
9130                 }
9131
9132                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9133                 assert_eq!(node_txn.len(), 4);
9134                 assert_eq!(node_txn[3].input.len(), 1);
9135                 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
9136
9137                 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
9138                 let spend_txn = check_spendable_outputs!(nodes[0], 1);
9139                 assert_eq!(spend_txn.len(), 5);
9140                 assert_eq!(spend_txn[0], spend_txn[2]);
9141                 assert_eq!(spend_txn[1], spend_txn[3]);
9142                 check_spends!(spend_txn[0], revoked_local_txn[0].clone()); // spending to_remote output from revoked local tx
9143                 check_spends!(spend_txn[1], node_txn[2].clone()); // spending justice tx output from revoked local tx htlc received output
9144                 check_spends!(spend_txn[4], node_txn[3].clone()); // spending justice tx output on htlc success tx
9145         }
9146
9147         #[test]
9148         fn test_onchain_to_onchain_claim() {
9149                 // Test that in case of channel closure, we detect the state of output thanks to
9150                 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
9151                 // First, have C claim an HTLC against its own latest commitment transaction.
9152                 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
9153                 // channel.
9154                 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
9155                 // gets broadcast.
9156
9157                 let nodes = create_network(3);
9158
9159                 // Create some initial channels
9160                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9161                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
9162
9163                 // Rebalance the network a bit by relaying one payment through all the channels ...
9164                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
9165                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
9166
9167                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
9168                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9169                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
9170                 check_spends!(commitment_tx[0], chan_2.3.clone());
9171                 nodes[2].node.claim_funds(payment_preimage);
9172                 check_added_monitors!(nodes[2], 1);
9173                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9174                 assert!(updates.update_add_htlcs.is_empty());
9175                 assert!(updates.update_fail_htlcs.is_empty());
9176                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
9177                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9178
9179                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
9180                 let events = nodes[2].node.get_and_clear_pending_msg_events();
9181                 assert_eq!(events.len(), 1);
9182                 match events[0] {
9183                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9184                         _ => panic!("Unexpected event"),
9185                 }
9186
9187                 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
9188                 assert_eq!(c_txn.len(), 3);
9189                 assert_eq!(c_txn[0], c_txn[2]);
9190                 assert_eq!(commitment_tx[0], c_txn[1]);
9191                 check_spends!(c_txn[1], chan_2.3.clone());
9192                 check_spends!(c_txn[2], c_txn[1].clone());
9193                 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
9194                 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9195                 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
9196                 assert_eq!(c_txn[0].lock_time, 0); // Success tx
9197
9198                 // 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
9199                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
9200                 {
9201                         let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9202                         assert_eq!(b_txn.len(), 4);
9203                         assert_eq!(b_txn[0], b_txn[3]);
9204                         check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
9205                         check_spends!(b_txn[2], b_txn[1].clone()); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
9206                         assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9207                         assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
9208                         assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
9209                         check_spends!(b_txn[0], c_txn[1].clone()); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
9210                         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9211                         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
9212                         assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
9213                         b_txn.clear();
9214                 }
9215                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
9216                 check_added_monitors!(nodes[1], 1);
9217                 match msg_events[0] {
9218                         MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
9219                         _ => panic!("Unexpected event"),
9220                 }
9221                 match msg_events[1] {
9222                         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, .. } } => {
9223                                 assert!(update_add_htlcs.is_empty());
9224                                 assert!(update_fail_htlcs.is_empty());
9225                                 assert_eq!(update_fulfill_htlcs.len(), 1);
9226                                 assert!(update_fail_malformed_htlcs.is_empty());
9227                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
9228                         },
9229                         _ => panic!("Unexpected event"),
9230                 };
9231                 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
9232                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9233                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
9234                 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9235                 assert_eq!(b_txn.len(), 3);
9236                 check_spends!(b_txn[1], chan_1.3); // Local commitment tx, issued by ChannelManager
9237                 assert_eq!(b_txn[0], b_txn[2]); // HTLC-Success tx, issued by ChannelMonitor, * 2 due to block rescan
9238                 check_spends!(b_txn[0], commitment_tx[0].clone());
9239                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9240                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
9241                 assert_eq!(b_txn[2].lock_time, 0); // Success tx
9242                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
9243                 match msg_events[0] {
9244                         MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
9245                         _ => panic!("Unexpected event"),
9246                 }
9247         }
9248
9249         #[test]
9250         fn test_duplicate_payment_hash_one_failure_one_success() {
9251                 // Topology : A --> B --> C
9252                 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
9253                 let mut nodes = create_network(3);
9254
9255                 create_announced_chan_between_nodes(&nodes, 0, 1);
9256                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
9257
9258                 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
9259                 *nodes[0].network_payment_count.borrow_mut() -= 1;
9260                 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
9261
9262                 let commitment_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
9263                 assert_eq!(commitment_txn[0].input.len(), 1);
9264                 check_spends!(commitment_txn[0], chan_2.3.clone());
9265
9266                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9267                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
9268                 let htlc_timeout_tx;
9269                 { // Extract one of the two HTLC-Timeout transaction
9270                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9271                         assert_eq!(node_txn.len(), 7);
9272                         assert_eq!(node_txn[0], node_txn[5]);
9273                         assert_eq!(node_txn[1], node_txn[6]);
9274                         check_spends!(node_txn[0], commitment_txn[0].clone());
9275                         assert_eq!(node_txn[0].input.len(), 1);
9276                         check_spends!(node_txn[1], commitment_txn[0].clone());
9277                         assert_eq!(node_txn[1].input.len(), 1);
9278                         assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
9279                         check_spends!(node_txn[2], chan_2.3.clone());
9280                         check_spends!(node_txn[3], node_txn[2].clone());
9281                         check_spends!(node_txn[4], node_txn[2].clone());
9282                         htlc_timeout_tx = node_txn[1].clone();
9283                 }
9284
9285                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9286                 match events[0] {
9287                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9288                         _ => panic!("Unexepected event"),
9289                 }
9290
9291                 nodes[2].node.claim_funds(our_payment_preimage);
9292                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
9293                 check_added_monitors!(nodes[2], 2);
9294                 let events = nodes[2].node.get_and_clear_pending_msg_events();
9295                 match events[0] {
9296                         MessageSendEvent::UpdateHTLCs { .. } => {},
9297                         _ => panic!("Unexpected event"),
9298                 }
9299                 match events[1] {
9300                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9301                         _ => panic!("Unexepected event"),
9302                 }
9303                 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9304                 assert_eq!(htlc_success_txn.len(), 5);
9305                 check_spends!(htlc_success_txn[2], chan_2.3.clone());
9306                 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
9307                 assert_eq!(htlc_success_txn[0].input.len(), 1);
9308                 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9309                 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
9310                 assert_eq!(htlc_success_txn[1].input.len(), 1);
9311                 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9312                 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
9313                 check_spends!(htlc_success_txn[0], commitment_txn[0].clone());
9314                 check_spends!(htlc_success_txn[1], commitment_txn[0].clone());
9315
9316                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
9317                 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9318                 assert!(htlc_updates.update_add_htlcs.is_empty());
9319                 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
9320                 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
9321                 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
9322                 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
9323                 check_added_monitors!(nodes[1], 1);
9324
9325                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]).unwrap();
9326                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9327                 {
9328                         commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
9329                         let events = nodes[0].node.get_and_clear_pending_msg_events();
9330                         assert_eq!(events.len(), 1);
9331                         match events[0] {
9332                                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
9333                                 },
9334                                 _ => { panic!("Unexpected event"); }
9335                         }
9336                 }
9337                 let events = nodes[0].node.get_and_clear_pending_events();
9338                 match events[0] {
9339                         Event::PaymentFailed { ref payment_hash, .. } => {
9340                                 assert_eq!(*payment_hash, duplicate_payment_hash);
9341                         }
9342                         _ => panic!("Unexpected event"),
9343                 }
9344
9345                 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
9346                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
9347                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9348                 assert!(updates.update_add_htlcs.is_empty());
9349                 assert!(updates.update_fail_htlcs.is_empty());
9350                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
9351                 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
9352                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9353                 check_added_monitors!(nodes[1], 1);
9354
9355                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
9356                 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
9357
9358                 let events = nodes[0].node.get_and_clear_pending_events();
9359                 match events[0] {
9360                         Event::PaymentSent { ref payment_preimage } => {
9361                                 assert_eq!(*payment_preimage, our_payment_preimage);
9362                         }
9363                         _ => panic!("Unexpected event"),
9364                 }
9365         }
9366
9367         #[test]
9368         fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
9369                 let nodes = create_network(2);
9370
9371                 // Create some initial channels
9372                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9373
9374                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
9375                 let local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9376                 assert_eq!(local_txn[0].input.len(), 1);
9377                 check_spends!(local_txn[0], chan_1.3.clone());
9378
9379                 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
9380                 nodes[1].node.claim_funds(payment_preimage);
9381                 check_added_monitors!(nodes[1], 1);
9382                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9383                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
9384                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9385                 match events[0] {
9386                         MessageSendEvent::UpdateHTLCs { .. } => {},
9387                         _ => panic!("Unexpected event"),
9388                 }
9389                 match events[1] {
9390                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9391                         _ => panic!("Unexepected event"),
9392                 }
9393                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9394                 assert_eq!(node_txn[0].input.len(), 1);
9395                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9396                 check_spends!(node_txn[0], local_txn[0].clone());
9397
9398                 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
9399                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9400                 assert_eq!(spend_txn.len(), 2);
9401                 check_spends!(spend_txn[0], node_txn[0].clone());
9402                 check_spends!(spend_txn[1], node_txn[2].clone());
9403         }
9404
9405         #[test]
9406         fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
9407                 let nodes = create_network(2);
9408
9409                 // Create some initial channels
9410                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9411
9412                 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
9413                 let local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9414                 assert_eq!(local_txn[0].input.len(), 1);
9415                 check_spends!(local_txn[0], chan_1.3.clone());
9416
9417                 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
9418                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9419                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
9420                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9421                 match events[0] {
9422                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9423                         _ => panic!("Unexepected event"),
9424                 }
9425                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9426                 assert_eq!(node_txn[0].input.len(), 1);
9427                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9428                 check_spends!(node_txn[0], local_txn[0].clone());
9429
9430                 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
9431                 let spend_txn = check_spendable_outputs!(nodes[0], 1);
9432                 assert_eq!(spend_txn.len(), 8);
9433                 assert_eq!(spend_txn[0], spend_txn[2]);
9434                 assert_eq!(spend_txn[0], spend_txn[4]);
9435                 assert_eq!(spend_txn[0], spend_txn[6]);
9436                 assert_eq!(spend_txn[1], spend_txn[3]);
9437                 assert_eq!(spend_txn[1], spend_txn[5]);
9438                 assert_eq!(spend_txn[1], spend_txn[7]);
9439                 check_spends!(spend_txn[0], local_txn[0].clone());
9440                 check_spends!(spend_txn[1], node_txn[0].clone());
9441         }
9442
9443         #[test]
9444         fn test_static_output_closing_tx() {
9445                 let nodes = create_network(2);
9446
9447                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
9448
9449                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
9450                 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
9451
9452                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9453                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
9454                 let spend_txn = check_spendable_outputs!(nodes[0], 2);
9455                 assert_eq!(spend_txn.len(), 1);
9456                 check_spends!(spend_txn[0], closing_tx.clone());
9457
9458                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
9459                 let spend_txn = check_spendable_outputs!(nodes[1], 2);
9460                 assert_eq!(spend_txn.len(), 1);
9461                 check_spends!(spend_txn[0], closing_tx);
9462         }
9463 }