Replace some unknown_next_peer by permanent_channel_failure
[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 { .. } => {
1558                                 log_trace!(self, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1559                                 mem::drop(channel_state_lock);
1560                                 if let &HTLCFailReason::ErrorPacket { ref err } = &onion_error {
1561                                         let (channel_update, payment_retryable) = self.process_onion_failure(&source, err.data.clone());
1562                                         if let Some(update) = channel_update {
1563                                                 self.channel_state.lock().unwrap().pending_msg_events.push(
1564                                                         events::MessageSendEvent::PaymentFailureNetworkUpdate {
1565                                                                 update,
1566                                                         }
1567                                                 );
1568                                         }
1569                                         self.pending_events.lock().unwrap().push(events::Event::PaymentFailed {
1570                                                 payment_hash: payment_hash.clone(),
1571                                                 rejected_by_dest: !payment_retryable,
1572                                         });
1573                                 } else {
1574                                         //TODO: Pass this back (see GH #243)
1575                                         self.pending_events.lock().unwrap().push(events::Event::PaymentFailed {
1576                                                 payment_hash: payment_hash.clone(),
1577                                                 rejected_by_dest: false, // We failed it ourselves, can't blame them
1578                                         });
1579                                 }
1580                         },
1581                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
1582                                 let err_packet = match onion_error {
1583                                         HTLCFailReason::Reason { failure_code, data } => {
1584                                                 log_trace!(self, "Failing HTLC with payment_hash {} backwards from us with code {}", log_bytes!(payment_hash.0), failure_code);
1585                                                 let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1586                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1587                                         },
1588                                         HTLCFailReason::ErrorPacket { err } => {
1589                                                 log_trace!(self, "Failing HTLC with payment_hash {} backwards with pre-built ErrorPacket", log_bytes!(payment_hash.0));
1590                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1591                                         }
1592                                 };
1593
1594                                 let channel_state = channel_state_lock.borrow_parts();
1595
1596                                 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1597                                         Some(chan_id) => chan_id.clone(),
1598                                         None => return
1599                                 };
1600
1601                                 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1602                                 match chan.get_update_fail_htlc_and_commit(htlc_id, err_packet) {
1603                                         Ok(Some((msg, commitment_msg, chan_monitor))) => {
1604                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1605                                                         unimplemented!();
1606                                                 }
1607                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1608                                                         node_id: chan.get_their_node_id(),
1609                                                         updates: msgs::CommitmentUpdate {
1610                                                                 update_add_htlcs: Vec::new(),
1611                                                                 update_fulfill_htlcs: Vec::new(),
1612                                                                 update_fail_htlcs: vec![msg],
1613                                                                 update_fail_malformed_htlcs: Vec::new(),
1614                                                                 update_fee: None,
1615                                                                 commitment_signed: commitment_msg,
1616                                                         },
1617                                                 });
1618                                         },
1619                                         Ok(None) => {},
1620                                         Err(_e) => {
1621                                                 //TODO: Do something with e?
1622                                                 return;
1623                                         },
1624                                 }
1625                         },
1626                 }
1627         }
1628
1629         /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1630         /// generating message events for the net layer to claim the payment, if possible. Thus, you
1631         /// should probably kick the net layer to go send messages if this returns true!
1632         ///
1633         /// May panic if called except in response to a PaymentReceived event.
1634         pub fn claim_funds(&self, payment_preimage: PaymentPreimage) -> bool {
1635                 let mut sha = Sha256::new();
1636                 sha.input(&payment_preimage.0[..]);
1637                 let mut payment_hash = PaymentHash([0; 32]);
1638                 sha.result(&mut payment_hash.0[..]);
1639
1640                 let _ = self.total_consistency_lock.read().unwrap();
1641
1642                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1643                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&payment_hash);
1644                 if let Some(mut sources) = removed_source {
1645                         for htlc_with_hash in sources.drain(..) {
1646                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1647                                 self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_preimage);
1648                         }
1649                         true
1650                 } else { false }
1651         }
1652         fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_preimage: PaymentPreimage) {
1653                 match source {
1654                         HTLCSource::OutboundRoute { .. } => {
1655                                 mem::drop(channel_state_lock);
1656                                 let mut pending_events = self.pending_events.lock().unwrap();
1657                                 pending_events.push(events::Event::PaymentSent {
1658                                         payment_preimage
1659                                 });
1660                         },
1661                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, .. }) => {
1662                                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1663                                 let channel_state = channel_state_lock.borrow_parts();
1664
1665                                 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1666                                         Some(chan_id) => chan_id.clone(),
1667                                         None => {
1668                                                 // TODO: There is probably a channel manager somewhere that needs to
1669                                                 // learn the preimage as the channel already hit the chain and that's
1670                                                 // why its missing.
1671                                                 return
1672                                         }
1673                                 };
1674
1675                                 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1676                                 match chan.get_update_fulfill_htlc_and_commit(htlc_id, payment_preimage) {
1677                                         Ok((msgs, monitor_option)) => {
1678                                                 if let Some(chan_monitor) = monitor_option {
1679                                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1680                                                                 unimplemented!();// but def dont push the event...
1681                                                         }
1682                                                 }
1683                                                 if let Some((msg, commitment_signed)) = msgs {
1684                                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1685                                                                 node_id: chan.get_their_node_id(),
1686                                                                 updates: msgs::CommitmentUpdate {
1687                                                                         update_add_htlcs: Vec::new(),
1688                                                                         update_fulfill_htlcs: vec![msg],
1689                                                                         update_fail_htlcs: Vec::new(),
1690                                                                         update_fail_malformed_htlcs: Vec::new(),
1691                                                                         update_fee: None,
1692                                                                         commitment_signed,
1693                                                                 }
1694                                                         });
1695                                                 }
1696                                         },
1697                                         Err(_e) => {
1698                                                 // TODO: There is probably a channel manager somewhere that needs to
1699                                                 // learn the preimage as the channel may be about to hit the chain.
1700                                                 //TODO: Do something with e?
1701                                                 return
1702                                         },
1703                                 }
1704                         },
1705                 }
1706         }
1707
1708         /// Gets the node_id held by this ChannelManager
1709         pub fn get_our_node_id(&self) -> PublicKey {
1710                 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
1711         }
1712
1713         /// Used to restore channels to normal operation after a
1714         /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
1715         /// operation.
1716         pub fn test_restore_channel_monitor(&self) {
1717                 let mut close_results = Vec::new();
1718                 let mut htlc_forwards = Vec::new();
1719                 let mut htlc_failures = Vec::new();
1720                 let _ = self.total_consistency_lock.read().unwrap();
1721
1722                 {
1723                         let mut channel_lock = self.channel_state.lock().unwrap();
1724                         let channel_state = channel_lock.borrow_parts();
1725                         let short_to_id = channel_state.short_to_id;
1726                         let pending_msg_events = channel_state.pending_msg_events;
1727                         channel_state.by_id.retain(|_, channel| {
1728                                 if channel.is_awaiting_monitor_update() {
1729                                         let chan_monitor = channel.channel_monitor();
1730                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1731                                                 match e {
1732                                                         ChannelMonitorUpdateErr::PermanentFailure => {
1733                                                                 // TODO: There may be some pending HTLCs that we intended to fail
1734                                                                 // backwards when a monitor update failed. We should make sure
1735                                                                 // knowledge of those gets moved into the appropriate in-memory
1736                                                                 // ChannelMonitor and they get failed backwards once we get
1737                                                                 // on-chain confirmations.
1738                                                                 // Note I think #198 addresses this, so once its merged a test
1739                                                                 // should be written.
1740                                                                 if let Some(short_id) = channel.get_short_channel_id() {
1741                                                                         short_to_id.remove(&short_id);
1742                                                                 }
1743                                                                 close_results.push(channel.force_shutdown());
1744                                                                 if let Ok(update) = self.get_channel_update(&channel) {
1745                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1746                                                                                 msg: update
1747                                                                         });
1748                                                                 }
1749                                                                 false
1750                                                         },
1751                                                         ChannelMonitorUpdateErr::TemporaryFailure => true,
1752                                                 }
1753                                         } else {
1754                                                 let (raa, commitment_update, order, pending_forwards, mut pending_failures) = channel.monitor_updating_restored();
1755                                                 if !pending_forwards.is_empty() {
1756                                                         htlc_forwards.push((channel.get_short_channel_id().expect("We can't have pending forwards before funding confirmation"), pending_forwards));
1757                                                 }
1758                                                 htlc_failures.append(&mut pending_failures);
1759
1760                                                 macro_rules! handle_cs { () => {
1761                                                         if let Some(update) = commitment_update {
1762                                                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1763                                                                         node_id: channel.get_their_node_id(),
1764                                                                         updates: update,
1765                                                                 });
1766                                                         }
1767                                                 } }
1768                                                 macro_rules! handle_raa { () => {
1769                                                         if let Some(revoke_and_ack) = raa {
1770                                                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
1771                                                                         node_id: channel.get_their_node_id(),
1772                                                                         msg: revoke_and_ack,
1773                                                                 });
1774                                                         }
1775                                                 } }
1776                                                 match order {
1777                                                         RAACommitmentOrder::CommitmentFirst => {
1778                                                                 handle_cs!();
1779                                                                 handle_raa!();
1780                                                         },
1781                                                         RAACommitmentOrder::RevokeAndACKFirst => {
1782                                                                 handle_raa!();
1783                                                                 handle_cs!();
1784                                                         },
1785                                                 }
1786                                                 true
1787                                         }
1788                                 } else { true }
1789                         });
1790                 }
1791
1792                 for failure in htlc_failures.drain(..) {
1793                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
1794                 }
1795                 self.forward_htlcs(&mut htlc_forwards[..]);
1796
1797                 for res in close_results.drain(..) {
1798                         self.finish_force_close_channel(res);
1799                 }
1800         }
1801
1802         fn internal_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
1803                 if msg.chain_hash != self.genesis_hash {
1804                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash", msg.temporary_channel_id.clone()));
1805                 }
1806
1807                 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)
1808                         .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
1809                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1810                 let channel_state = channel_state_lock.borrow_parts();
1811                 match channel_state.by_id.entry(channel.channel_id()) {
1812                         hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!", msg.temporary_channel_id.clone())),
1813                         hash_map::Entry::Vacant(entry) => {
1814                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
1815                                         node_id: their_node_id.clone(),
1816                                         msg: channel.get_accept_channel(),
1817                                 });
1818                                 entry.insert(channel);
1819                         }
1820                 }
1821                 Ok(())
1822         }
1823
1824         fn internal_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
1825                 let (value, output_script, user_id) = {
1826                         let mut channel_lock = self.channel_state.lock().unwrap();
1827                         let channel_state = channel_lock.borrow_parts();
1828                         match channel_state.by_id.entry(msg.temporary_channel_id) {
1829                                 hash_map::Entry::Occupied(mut chan) => {
1830                                         if chan.get().get_their_node_id() != *their_node_id {
1831                                                 //TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
1832                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1833                                         }
1834                                         try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration), channel_state, chan);
1835                                         (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
1836                                 },
1837                                 //TODO: same as above
1838                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1839                         }
1840                 };
1841                 let mut pending_events = self.pending_events.lock().unwrap();
1842                 pending_events.push(events::Event::FundingGenerationReady {
1843                         temporary_channel_id: msg.temporary_channel_id,
1844                         channel_value_satoshis: value,
1845                         output_script: output_script,
1846                         user_channel_id: user_id,
1847                 });
1848                 Ok(())
1849         }
1850
1851         fn internal_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
1852                 let ((funding_msg, monitor_update), chan) = {
1853                         let mut channel_lock = self.channel_state.lock().unwrap();
1854                         let channel_state = channel_lock.borrow_parts();
1855                         match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
1856                                 hash_map::Entry::Occupied(mut chan) => {
1857                                         if chan.get().get_their_node_id() != *their_node_id {
1858                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1859                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1860                                         }
1861                                         (try_chan_entry!(self, chan.get_mut().funding_created(msg), channel_state, chan), chan.remove())
1862                                 },
1863                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1864                         }
1865                 };
1866                 // Because we have exclusive ownership of the channel here we can release the channel_state
1867                 // lock before add_update_monitor
1868                 if let Err(_e) = self.monitor.add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) {
1869                         unimplemented!();
1870                 }
1871                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1872                 let channel_state = channel_state_lock.borrow_parts();
1873                 match channel_state.by_id.entry(funding_msg.channel_id) {
1874                         hash_map::Entry::Occupied(_) => {
1875                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id", funding_msg.channel_id))
1876                         },
1877                         hash_map::Entry::Vacant(e) => {
1878                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
1879                                         node_id: their_node_id.clone(),
1880                                         msg: funding_msg,
1881                                 });
1882                                 e.insert(chan);
1883                         }
1884                 }
1885                 Ok(())
1886         }
1887
1888         fn internal_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
1889                 let (funding_txo, user_id) = {
1890                         let mut channel_lock = self.channel_state.lock().unwrap();
1891                         let channel_state = channel_lock.borrow_parts();
1892                         match channel_state.by_id.entry(msg.channel_id) {
1893                                 hash_map::Entry::Occupied(mut chan) => {
1894                                         if chan.get().get_their_node_id() != *their_node_id {
1895                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1896                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1897                                         }
1898                                         let chan_monitor = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
1899                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1900                                                 unimplemented!();
1901                                         }
1902                                         (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())
1903                                 },
1904                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1905                         }
1906                 };
1907                 let mut pending_events = self.pending_events.lock().unwrap();
1908                 pending_events.push(events::Event::FundingBroadcastSafe {
1909                         funding_txo: funding_txo,
1910                         user_channel_id: user_id,
1911                 });
1912                 Ok(())
1913         }
1914
1915         fn internal_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), MsgHandleErrInternal> {
1916                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1917                 let channel_state = channel_state_lock.borrow_parts();
1918                 match channel_state.by_id.entry(msg.channel_id) {
1919                         hash_map::Entry::Occupied(mut chan) => {
1920                                 if chan.get().get_their_node_id() != *their_node_id {
1921                                         //TODO: here and below MsgHandleErrInternal, #153 case
1922                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1923                                 }
1924                                 try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
1925                                 if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
1926                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
1927                                                 node_id: their_node_id.clone(),
1928                                                 msg: announcement_sigs,
1929                                         });
1930                                 }
1931                                 Ok(())
1932                         },
1933                         hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1934                 }
1935         }
1936
1937         fn internal_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
1938                 let (mut dropped_htlcs, chan_option) = {
1939                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1940                         let channel_state = channel_state_lock.borrow_parts();
1941
1942                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1943                                 hash_map::Entry::Occupied(mut chan_entry) => {
1944                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1945                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1946                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1947                                         }
1948                                         let (shutdown, closing_signed, dropped_htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg), channel_state, chan_entry);
1949                                         if let Some(msg) = shutdown {
1950                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
1951                                                         node_id: their_node_id.clone(),
1952                                                         msg,
1953                                                 });
1954                                         }
1955                                         if let Some(msg) = closing_signed {
1956                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1957                                                         node_id: their_node_id.clone(),
1958                                                         msg,
1959                                                 });
1960                                         }
1961                                         if chan_entry.get().is_shutdown() {
1962                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1963                                                         channel_state.short_to_id.remove(&short_id);
1964                                                 }
1965                                                 (dropped_htlcs, Some(chan_entry.remove_entry().1))
1966                                         } else { (dropped_htlcs, None) }
1967                                 },
1968                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1969                         }
1970                 };
1971                 for htlc_source in dropped_htlcs.drain(..) {
1972                         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() });
1973                 }
1974                 if let Some(chan) = chan_option {
1975                         if let Ok(update) = self.get_channel_update(&chan) {
1976                                 let mut channel_state = self.channel_state.lock().unwrap();
1977                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1978                                         msg: update
1979                                 });
1980                         }
1981                 }
1982                 Ok(())
1983         }
1984
1985         fn internal_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
1986                 let (tx, chan_option) = {
1987                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1988                         let channel_state = channel_state_lock.borrow_parts();
1989                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1990                                 hash_map::Entry::Occupied(mut chan_entry) => {
1991                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1992                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1993                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1994                                         }
1995                                         let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg), channel_state, chan_entry);
1996                                         if let Some(msg) = closing_signed {
1997                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1998                                                         node_id: their_node_id.clone(),
1999                                                         msg,
2000                                                 });
2001                                         }
2002                                         if tx.is_some() {
2003                                                 // We're done with this channel, we've got a signed closing transaction and
2004                                                 // will send the closing_signed back to the remote peer upon return. This
2005                                                 // also implies there are no pending HTLCs left on the channel, so we can
2006                                                 // fully delete it from tracking (the channel monitor is still around to
2007                                                 // watch for old state broadcasts)!
2008                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2009                                                         channel_state.short_to_id.remove(&short_id);
2010                                                 }
2011                                                 (tx, Some(chan_entry.remove_entry().1))
2012                                         } else { (tx, None) }
2013                                 },
2014                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2015                         }
2016                 };
2017                 if let Some(broadcast_tx) = tx {
2018                         self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
2019                 }
2020                 if let Some(chan) = chan_option {
2021                         if let Ok(update) = self.get_channel_update(&chan) {
2022                                 let mut channel_state = self.channel_state.lock().unwrap();
2023                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2024                                         msg: update
2025                                 });
2026                         }
2027                 }
2028                 Ok(())
2029         }
2030
2031         fn internal_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
2032                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
2033                 //determine the state of the payment based on our response/if we forward anything/the time
2034                 //we take to respond. We should take care to avoid allowing such an attack.
2035                 //
2036                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
2037                 //us repeatedly garbled in different ways, and compare our error messages, which are
2038                 //encrypted with the same key. Its not immediately obvious how to usefully exploit that,
2039                 //but we should prevent it anyway.
2040
2041                 let (mut pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
2042                 let channel_state = channel_state_lock.borrow_parts();
2043
2044                 match channel_state.by_id.entry(msg.channel_id) {
2045                         hash_map::Entry::Occupied(mut chan) => {
2046                                 if chan.get().get_their_node_id() != *their_node_id {
2047                                         //TODO: here MsgHandleErrInternal, #153 case
2048                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2049                                 }
2050                                 if !chan.get().is_usable() {
2051                                         // If the update_add is completely bogus, the call will Err and we will close,
2052                                         // but if we've sent a shutdown and they haven't acknowledged it yet, we just
2053                                         // want to reject the new HTLC and fail it backwards instead of forwarding.
2054                                         if let PendingHTLCStatus::Forward(PendingForwardHTLCInfo { incoming_shared_secret, .. }) = pending_forward_info {
2055                                                 let chan_update = self.get_channel_update(chan.get());
2056                                                 pending_forward_info = PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
2057                                                         channel_id: msg.channel_id,
2058                                                         htlc_id: msg.htlc_id,
2059                                                         reason: if let Ok(update) = chan_update {
2060                                                                 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x1000|20, &update.encode_with_len()[..])
2061                                                         } else {
2062                                                                 // This can only happen if the channel isn't in the fully-funded
2063                                                                 // state yet, implying our counterparty is trying to route payments
2064                                                                 // over the channel back to themselves (cause no one else should
2065                                                                 // know the short_id is a lightning channel yet). We should have no
2066                                                                 // problem just calling this unknown_next_peer
2067                                                                 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x4000|10, &[])
2068                                                         },
2069                                                 }));
2070                                         }
2071                                 }
2072                                 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info), channel_state, chan);
2073                         },
2074                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2075                 }
2076                 Ok(())
2077         }
2078
2079         fn internal_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
2080                 let mut channel_lock = self.channel_state.lock().unwrap();
2081                 let htlc_source = {
2082                         let channel_state = channel_lock.borrow_parts();
2083                         match channel_state.by_id.entry(msg.channel_id) {
2084                                 hash_map::Entry::Occupied(mut chan) => {
2085                                         if chan.get().get_their_node_id() != *their_node_id {
2086                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2087                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2088                                         }
2089                                         try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), channel_state, chan)
2090                                 },
2091                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2092                         }
2093                 };
2094                 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
2095                 Ok(())
2096         }
2097
2098         // Process failure we got back from upstream on a payment we sent. Returns update and a boolean
2099         // indicating that the payment itself failed
2100         fn process_onion_failure(&self, htlc_source: &HTLCSource, mut packet_decrypted: Vec<u8>) -> (Option<msgs::HTLCFailChannelUpdate>, bool) {
2101                 if let &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } = htlc_source {
2102                         macro_rules! onion_failure_log {
2103                                 ( $error_code_textual: expr, $error_code: expr, $reported_name: expr, $reported_value: expr ) => {
2104                                         log_trace!(self, "{}({:#x}) {}({})", $error_code_textual, $error_code, $reported_name, $reported_value);
2105                                 };
2106                                 ( $error_code_textual: expr, $error_code: expr ) => {
2107                                         log_trace!(self, "{}({})", $error_code_textual, $error_code);
2108                                 };
2109                         }
2110
2111                         const BADONION: u16 = 0x8000;
2112                         const PERM: u16 = 0x4000;
2113                         const UPDATE: u16 = 0x1000;
2114
2115                         let mut res = None;
2116                         let mut htlc_msat = *first_hop_htlc_msat;
2117
2118                         // Handle packed channel/node updates for passing back for the route handler
2119                         Self::construct_onion_keys_callback(&self.secp_ctx, route, session_priv, |shared_secret, _, _, route_hop| {
2120                                 if res.is_some() { return; }
2121
2122                                 let incoming_htlc_msat = htlc_msat;
2123                                 let amt_to_forward = htlc_msat - route_hop.fee_msat;
2124                                 htlc_msat = amt_to_forward;
2125
2126                                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret[..]);
2127
2128                                 let mut decryption_tmp = Vec::with_capacity(packet_decrypted.len());
2129                                 decryption_tmp.resize(packet_decrypted.len(), 0);
2130                                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
2131                                 chacha.process(&packet_decrypted, &mut decryption_tmp[..]);
2132                                 packet_decrypted = decryption_tmp;
2133
2134                                 let is_from_final_node = route.hops.last().unwrap().pubkey == route_hop.pubkey;
2135
2136                                 if let Ok(err_packet) = msgs::DecodedOnionErrorPacket::read(&mut Cursor::new(&packet_decrypted)) {
2137                                         let um = ChannelManager::gen_um_from_shared_secret(&shared_secret[..]);
2138                                         let mut hmac = Hmac::new(Sha256::new(), &um);
2139                                         hmac.input(&err_packet.encode()[32..]);
2140                                         let mut calc_tag = [0u8; 32];
2141                                         hmac.raw_result(&mut calc_tag);
2142
2143                                         if crypto::util::fixed_time_eq(&calc_tag, &err_packet.hmac) {
2144                                                 if err_packet.failuremsg.len() < 2 {
2145                                                         // Useless packet that we can't use but it passed HMAC, so it
2146                                                         // definitely came from the peer in question
2147                                                         res = Some((None, !is_from_final_node));
2148                                                 } else {
2149                                                         let error_code = byte_utils::slice_to_be16(&err_packet.failuremsg[0..2]);
2150
2151                                                         match error_code & 0xff {
2152                                                                 1|2|3 => {
2153                                                                         // either from an intermediate or final node
2154                                                                         //   invalid_realm(PERM|1),
2155                                                                         //   temporary_node_failure(NODE|2)
2156                                                                         //   permanent_node_failure(PERM|NODE|2)
2157                                                                         //   required_node_feature_mssing(PERM|NODE|3)
2158                                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2159                                                                                 node_id: route_hop.pubkey,
2160                                                                                 is_permanent: error_code & PERM == PERM,
2161                                                                         }), !(error_code & PERM == PERM && is_from_final_node)));
2162                                                                         // node returning invalid_realm is removed from network_map,
2163                                                                         // although NODE flag is not set, TODO: or remove channel only?
2164                                                                         // retry payment when removed node is not a final node
2165                                                                         return;
2166                                                                 },
2167                                                                 _ => {}
2168                                                         }
2169
2170                                                         if is_from_final_node {
2171                                                                 let payment_retryable = match error_code {
2172                                                                         c if c == PERM|15 => false, // unknown_payment_hash
2173                                                                         c if c == PERM|16 => false, // incorrect_payment_amount
2174                                                                         17 => true, // final_expiry_too_soon
2175                                                                         18 if err_packet.failuremsg.len() == 6 => { // final_incorrect_cltv_expiry
2176                                                                                 let _reported_cltv_expiry = byte_utils::slice_to_be32(&err_packet.failuremsg[2..2+4]);
2177                                                                                 true
2178                                                                         },
2179                                                                         19 if err_packet.failuremsg.len() == 10 => { // final_incorrect_htlc_amount
2180                                                                                 let _reported_incoming_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
2181                                                                                 true
2182                                                                         },
2183                                                                         _ => {
2184                                                                                 // A final node has sent us either an invalid code or an error_code that
2185                                                                                 // MUST be sent from the processing node, or the formmat of failuremsg
2186                                                                                 // does not coform to the spec.
2187                                                                                 // Remove it from the network map and don't may retry payment
2188                                                                                 res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2189                                                                                         node_id: route_hop.pubkey,
2190                                                                                         is_permanent: true,
2191                                                                                 }), false));
2192                                                                                 return;
2193                                                                         }
2194                                                                 };
2195                                                                 res = Some((None, payment_retryable));
2196                                                                 return;
2197                                                         }
2198
2199                                                         // now, error_code should be only from the intermediate nodes
2200                                                         match error_code {
2201                                                                 _c if error_code & PERM == PERM => {
2202                                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
2203                                                                                 short_channel_id: route_hop.short_channel_id,
2204                                                                                 is_permanent: true,
2205                                                                         }), false));
2206                                                                 },
2207                                                                 _c if error_code & UPDATE == UPDATE => {
2208                                                                         let offset = match error_code {
2209                                                                                 c if c == UPDATE|7  => 0, // temporary_channel_failure
2210                                                                                 c if c == UPDATE|11 => 8, // amount_below_minimum
2211                                                                                 c if c == UPDATE|12 => 8, // fee_insufficient
2212                                                                                 c if c == UPDATE|13 => 4, // incorrect_cltv_expiry
2213                                                                                 c if c == UPDATE|14 => 0, // expiry_too_soon
2214                                                                                 c if c == UPDATE|20 => 2, // channel_disabled
2215                                                                                 _ =>  {
2216                                                                                         // node sending unknown code
2217                                                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2218                                                                                                 node_id: route_hop.pubkey,
2219                                                                                                 is_permanent: true,
2220                                                                                         }), false));
2221                                                                                         return;
2222                                                                                 }
2223                                                                         };
2224
2225                                                                         if err_packet.failuremsg.len() >= offset + 2 {
2226                                                                                 let update_len = byte_utils::slice_to_be16(&err_packet.failuremsg[offset+2..offset+4]) as usize;
2227                                                                                 if err_packet.failuremsg.len() >= offset + 4 + update_len {
2228                                                                                         if let Ok(chan_update) = msgs::ChannelUpdate::read(&mut Cursor::new(&err_packet.failuremsg[offset + 4..offset + 4 + update_len])) {
2229                                                                                                 // if channel_update should NOT have caused the failure:
2230                                                                                                 // MAY treat the channel_update as invalid.
2231                                                                                                 let is_chan_update_invalid = match error_code {
2232                                                                                                         c if c == UPDATE|7 => { // temporary_channel_failure
2233                                                                                                                 false
2234                                                                                                         },
2235                                                                                                         c if c == UPDATE|11 => { // amount_below_minimum
2236                                                                                                                 let reported_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
2237                                                                                                                 onion_failure_log!("amount_below_minimum", UPDATE|11, "htlc_msat", reported_htlc_msat);
2238                                                                                                                 incoming_htlc_msat > chan_update.contents.htlc_minimum_msat
2239                                                                                                         },
2240                                                                                                         c if c == UPDATE|12 => { // fee_insufficient
2241                                                                                                                 let reported_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
2242                                                                                                                 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) });
2243                                                                                                                 onion_failure_log!("fee_insufficient", UPDATE|12, "htlc_msat", reported_htlc_msat);
2244                                                                                                                 new_fee.is_none() || incoming_htlc_msat >= new_fee.unwrap() && incoming_htlc_msat >= amt_to_forward + new_fee.unwrap()
2245                                                                                                         }
2246                                                                                                         c if c == UPDATE|13 => { // incorrect_cltv_expiry
2247                                                                                                                 let reported_cltv_expiry = byte_utils::slice_to_be32(&err_packet.failuremsg[2..2+4]);
2248                                                                                                                 onion_failure_log!("incorrect_cltv_expiry", UPDATE|13, "cltv_expiry", reported_cltv_expiry);
2249                                                                                                                 route_hop.cltv_expiry_delta as u16 >= chan_update.contents.cltv_expiry_delta
2250                                                                                                         },
2251                                                                                                         c if c == UPDATE|20 => { // channel_disabled
2252                                                                                                                 let reported_flags = byte_utils::slice_to_be16(&err_packet.failuremsg[2..2+2]);
2253                                                                                                                 onion_failure_log!("channel_disabled", UPDATE|20, "flags", reported_flags);
2254                                                                                                                 chan_update.contents.flags & 0x01 == 0x01
2255                                                                                                         },
2256                                                                                                         c if c == UPDATE|21 => true, // expiry_too_far
2257                                                                                                         _ => { unreachable!(); },
2258                                                                                                 };
2259
2260                                                                                                 let msg = if is_chan_update_invalid { None } else {
2261                                                                                                         Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {
2262                                                                                                                 msg: chan_update,
2263                                                                                                         })
2264                                                                                                 };
2265                                                                                                 res = Some((msg, true));
2266                                                                                                 return;
2267                                                                                         }
2268                                                                                 }
2269                                                                         }
2270                                                                 },
2271                                                                 _c if error_code & BADONION == BADONION => {
2272                                                                         //TODO
2273                                                                 },
2274                                                                 14 => { // expiry_too_soon
2275                                                                         res = Some((None, true));
2276                                                                         return;
2277                                                                 }
2278                                                                 _ => {
2279                                                                         // node sending unknown code
2280                                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2281                                                                                 node_id: route_hop.pubkey,
2282                                                                                 is_permanent: true,
2283                                                                         }), false));
2284                                                                         return;
2285                                                                 }
2286                                                         }
2287                                                 }
2288                                         }
2289                                 }
2290                         }).expect("Route that we sent via spontaneously grew invalid keys in the middle of it?");
2291                         res.unwrap_or((None, true))
2292                 } else { ((None, true)) }
2293         }
2294
2295         fn internal_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
2296                 let mut channel_lock = self.channel_state.lock().unwrap();
2297                 let channel_state = channel_lock.borrow_parts();
2298                 match channel_state.by_id.entry(msg.channel_id) {
2299                         hash_map::Entry::Occupied(mut chan) => {
2300                                 if chan.get().get_their_node_id() != *their_node_id {
2301                                         //TODO: here and below MsgHandleErrInternal, #153 case
2302                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2303                                 }
2304                                 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::ErrorPacket { err: msg.reason.clone() }), channel_state, chan);
2305                         },
2306                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2307                 }
2308                 Ok(())
2309         }
2310
2311         fn internal_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
2312                 let mut channel_lock = self.channel_state.lock().unwrap();
2313                 let channel_state = channel_lock.borrow_parts();
2314                 match channel_state.by_id.entry(msg.channel_id) {
2315                         hash_map::Entry::Occupied(mut chan) => {
2316                                 if chan.get().get_their_node_id() != *their_node_id {
2317                                         //TODO: here and below MsgHandleErrInternal, #153 case
2318                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2319                                 }
2320                                 if (msg.failure_code & 0x8000) == 0 {
2321                                         try_chan_entry!(self, Err(ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set")), channel_state, chan);
2322                                 }
2323                                 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);
2324                                 Ok(())
2325                         },
2326                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2327                 }
2328         }
2329
2330         fn internal_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
2331                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2332                 let channel_state = channel_state_lock.borrow_parts();
2333                 match channel_state.by_id.entry(msg.channel_id) {
2334                         hash_map::Entry::Occupied(mut chan) => {
2335                                 if chan.get().get_their_node_id() != *their_node_id {
2336                                         //TODO: here and below MsgHandleErrInternal, #153 case
2337                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2338                                 }
2339                                 let (revoke_and_ack, commitment_signed, closing_signed, chan_monitor) =
2340                                         try_chan_entry!(self, chan.get_mut().commitment_signed(&msg, &*self.fee_estimator), channel_state, chan);
2341                                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2342                                         return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, commitment_signed.is_some());
2343                                         //TODO: Rebroadcast closing_signed if present on monitor update restoration
2344                                 }
2345                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2346                                         node_id: their_node_id.clone(),
2347                                         msg: revoke_and_ack,
2348                                 });
2349                                 if let Some(msg) = commitment_signed {
2350                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2351                                                 node_id: their_node_id.clone(),
2352                                                 updates: msgs::CommitmentUpdate {
2353                                                         update_add_htlcs: Vec::new(),
2354                                                         update_fulfill_htlcs: Vec::new(),
2355                                                         update_fail_htlcs: Vec::new(),
2356                                                         update_fail_malformed_htlcs: Vec::new(),
2357                                                         update_fee: None,
2358                                                         commitment_signed: msg,
2359                                                 },
2360                                         });
2361                                 }
2362                                 if let Some(msg) = closing_signed {
2363                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2364                                                 node_id: their_node_id.clone(),
2365                                                 msg,
2366                                         });
2367                                 }
2368                                 Ok(())
2369                         },
2370                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2371                 }
2372         }
2373
2374         #[inline]
2375         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64)>)]) {
2376                 for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
2377                         let mut forward_event = None;
2378                         if !pending_forwards.is_empty() {
2379                                 let mut channel_state = self.channel_state.lock().unwrap();
2380                                 if channel_state.forward_htlcs.is_empty() {
2381                                         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));
2382                                         channel_state.next_forward = forward_event.unwrap();
2383                                 }
2384                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2385                                         match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
2386                                                 hash_map::Entry::Occupied(mut entry) => {
2387                                                         entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info });
2388                                                 },
2389                                                 hash_map::Entry::Vacant(entry) => {
2390                                                         entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info }));
2391                                                 }
2392                                         }
2393                                 }
2394                         }
2395                         match forward_event {
2396                                 Some(time) => {
2397                                         let mut pending_events = self.pending_events.lock().unwrap();
2398                                         pending_events.push(events::Event::PendingHTLCsForwardable {
2399                                                 time_forwardable: time
2400                                         });
2401                                 }
2402                                 None => {},
2403                         }
2404                 }
2405         }
2406
2407         fn internal_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
2408                 let (pending_forwards, mut pending_failures, short_channel_id) = {
2409                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2410                         let channel_state = channel_state_lock.borrow_parts();
2411                         match channel_state.by_id.entry(msg.channel_id) {
2412                                 hash_map::Entry::Occupied(mut chan) => {
2413                                         if chan.get().get_their_node_id() != *their_node_id {
2414                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2415                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2416                                         }
2417                                         let (commitment_update, pending_forwards, pending_failures, closing_signed, chan_monitor) =
2418                                                 try_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &*self.fee_estimator), channel_state, chan);
2419                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2420                                                 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, pending_forwards, pending_failures);
2421                                         }
2422                                         if let Some(updates) = commitment_update {
2423                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2424                                                         node_id: their_node_id.clone(),
2425                                                         updates,
2426                                                 });
2427                                         }
2428                                         if let Some(msg) = closing_signed {
2429                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2430                                                         node_id: their_node_id.clone(),
2431                                                         msg,
2432                                                 });
2433                                         }
2434                                         (pending_forwards, pending_failures, chan.get().get_short_channel_id().expect("RAA should only work on a short-id-available channel"))
2435                                 },
2436                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2437                         }
2438                 };
2439                 for failure in pending_failures.drain(..) {
2440                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2441                 }
2442                 self.forward_htlcs(&mut [(short_channel_id, pending_forwards)]);
2443
2444                 Ok(())
2445         }
2446
2447         fn internal_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2448                 let mut channel_lock = self.channel_state.lock().unwrap();
2449                 let channel_state = channel_lock.borrow_parts();
2450                 match channel_state.by_id.entry(msg.channel_id) {
2451                         hash_map::Entry::Occupied(mut chan) => {
2452                                 if chan.get().get_their_node_id() != *their_node_id {
2453                                         //TODO: here and below MsgHandleErrInternal, #153 case
2454                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2455                                 }
2456                                 try_chan_entry!(self, chan.get_mut().update_fee(&*self.fee_estimator, &msg), channel_state, chan);
2457                         },
2458                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2459                 }
2460                 Ok(())
2461         }
2462
2463         fn internal_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2464                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2465                 let channel_state = channel_state_lock.borrow_parts();
2466
2467                 match channel_state.by_id.entry(msg.channel_id) {
2468                         hash_map::Entry::Occupied(mut chan) => {
2469                                 if chan.get().get_their_node_id() != *their_node_id {
2470                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2471                                 }
2472                                 if !chan.get().is_usable() {
2473                                         return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Got an announcement_signatures before we were ready for it", action: Some(msgs::ErrorAction::IgnoreError)}));
2474                                 }
2475
2476                                 let our_node_id = self.get_our_node_id();
2477                                 let (announcement, our_bitcoin_sig) =
2478                                         try_chan_entry!(self, chan.get_mut().get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone()), channel_state, chan);
2479
2480                                 let were_node_one = announcement.node_id_1 == our_node_id;
2481                                 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
2482                                 if self.secp_ctx.verify(&msghash, &msg.node_signature, if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 }).is_err() ||
2483                                                 self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 }).is_err() {
2484                                         try_chan_entry!(self, Err(ChannelError::Close("Bad announcement_signatures node_signature")), channel_state, chan);
2485                                 }
2486
2487                                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2488
2489                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
2490                                         msg: msgs::ChannelAnnouncement {
2491                                                 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
2492                                                 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
2493                                                 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
2494                                                 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
2495                                                 contents: announcement,
2496                                         },
2497                                         update_msg: self.get_channel_update(chan.get()).unwrap(), // can only fail if we're not in a ready state
2498                                 });
2499                         },
2500                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2501                 }
2502                 Ok(())
2503         }
2504
2505         fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
2506                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2507                 let channel_state = channel_state_lock.borrow_parts();
2508
2509                 match channel_state.by_id.entry(msg.channel_id) {
2510                         hash_map::Entry::Occupied(mut chan) => {
2511                                 if chan.get().get_their_node_id() != *their_node_id {
2512                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2513                                 }
2514                                 let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, mut order, shutdown) =
2515                                         try_chan_entry!(self, chan.get_mut().channel_reestablish(msg), channel_state, chan);
2516                                 if let Some(monitor) = channel_monitor {
2517                                         if let Err(e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
2518                                                 // channel_reestablish doesn't guarantee the order it returns is sensical
2519                                                 // for the messages it returns, but if we're setting what messages to
2520                                                 // re-transmit on monitor update success, we need to make sure it is sane.
2521                                                 if revoke_and_ack.is_none() {
2522                                                         order = RAACommitmentOrder::CommitmentFirst;
2523                                                 }
2524                                                 if commitment_update.is_none() {
2525                                                         order = RAACommitmentOrder::RevokeAndACKFirst;
2526                                                 }
2527                                                 return_monitor_err!(self, e, channel_state, chan, order);
2528                                                 //TODO: Resend the funding_locked if needed once we get the monitor running again
2529                                         }
2530                                 }
2531                                 if let Some(msg) = funding_locked {
2532                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2533                                                 node_id: their_node_id.clone(),
2534                                                 msg
2535                                         });
2536                                 }
2537                                 macro_rules! send_raa { () => {
2538                                         if let Some(msg) = revoke_and_ack {
2539                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2540                                                         node_id: their_node_id.clone(),
2541                                                         msg
2542                                                 });
2543                                         }
2544                                 } }
2545                                 macro_rules! send_cu { () => {
2546                                         if let Some(updates) = commitment_update {
2547                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2548                                                         node_id: their_node_id.clone(),
2549                                                         updates
2550                                                 });
2551                                         }
2552                                 } }
2553                                 match order {
2554                                         RAACommitmentOrder::RevokeAndACKFirst => {
2555                                                 send_raa!();
2556                                                 send_cu!();
2557                                         },
2558                                         RAACommitmentOrder::CommitmentFirst => {
2559                                                 send_cu!();
2560                                                 send_raa!();
2561                                         },
2562                                 }
2563                                 if let Some(msg) = shutdown {
2564                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2565                                                 node_id: their_node_id.clone(),
2566                                                 msg,
2567                                         });
2568                                 }
2569                                 Ok(())
2570                         },
2571                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2572                 }
2573         }
2574
2575         /// Begin Update fee process. Allowed only on an outbound channel.
2576         /// If successful, will generate a UpdateHTLCs event, so you should probably poll
2577         /// PeerManager::process_events afterwards.
2578         /// Note: This API is likely to change!
2579         #[doc(hidden)]
2580         pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u64) -> Result<(), APIError> {
2581                 let _ = self.total_consistency_lock.read().unwrap();
2582                 let their_node_id;
2583                 let err: Result<(), _> = loop {
2584                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2585                         let channel_state = channel_state_lock.borrow_parts();
2586
2587                         match channel_state.by_id.entry(channel_id) {
2588                                 hash_map::Entry::Vacant(_) => return Err(APIError::APIMisuseError{err: "Failed to find corresponding channel"}),
2589                                 hash_map::Entry::Occupied(mut chan) => {
2590                                         if !chan.get().is_outbound() {
2591                                                 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel"});
2592                                         }
2593                                         if chan.get().is_awaiting_monitor_update() {
2594                                                 return Err(APIError::MonitorUpdateFailed);
2595                                         }
2596                                         if !chan.get().is_live() {
2597                                                 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected"});
2598                                         }
2599                                         their_node_id = chan.get().get_their_node_id();
2600                                         if let Some((update_fee, commitment_signed, chan_monitor)) =
2601                                                         break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw), channel_state, chan)
2602                                         {
2603                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2604                                                         unimplemented!();
2605                                                 }
2606                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2607                                                         node_id: chan.get().get_their_node_id(),
2608                                                         updates: msgs::CommitmentUpdate {
2609                                                                 update_add_htlcs: Vec::new(),
2610                                                                 update_fulfill_htlcs: Vec::new(),
2611                                                                 update_fail_htlcs: Vec::new(),
2612                                                                 update_fail_malformed_htlcs: Vec::new(),
2613                                                                 update_fee: Some(update_fee),
2614                                                                 commitment_signed,
2615                                                         },
2616                                                 });
2617                                         }
2618                                 },
2619                         }
2620                         return Ok(())
2621                 };
2622
2623                 match handle_error!(self, err, their_node_id) {
2624                         Ok(_) => unreachable!(),
2625                         Err(e) => {
2626                                 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
2627                                 } else {
2628                                         log_error!(self, "Got bad keys: {}!", e.err);
2629                                         let mut channel_state = self.channel_state.lock().unwrap();
2630                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
2631                                                 node_id: their_node_id,
2632                                                 action: e.action,
2633                                         });
2634                                 }
2635                                 Err(APIError::APIMisuseError { err: e.err })
2636                         },
2637                 }
2638         }
2639 }
2640
2641 impl events::MessageSendEventsProvider for ChannelManager {
2642         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
2643                 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2644                 // user to serialize a ChannelManager with pending events in it and lose those events on
2645                 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2646                 {
2647                         //TODO: This behavior should be documented.
2648                         for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2649                                 if let Some(preimage) = htlc_update.payment_preimage {
2650                                         log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2651                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2652                                 } else {
2653                                         log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2654                                         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() });
2655                                 }
2656                         }
2657                 }
2658
2659                 let mut ret = Vec::new();
2660                 let mut channel_state = self.channel_state.lock().unwrap();
2661                 mem::swap(&mut ret, &mut channel_state.pending_msg_events);
2662                 ret
2663         }
2664 }
2665
2666 impl events::EventsProvider for ChannelManager {
2667         fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
2668                 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2669                 // user to serialize a ChannelManager with pending events in it and lose those events on
2670                 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2671                 {
2672                         //TODO: This behavior should be documented.
2673                         for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2674                                 if let Some(preimage) = htlc_update.payment_preimage {
2675                                         log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2676                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2677                                 } else {
2678                                         log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2679                                         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() });
2680                                 }
2681                         }
2682                 }
2683
2684                 let mut ret = Vec::new();
2685                 let mut pending_events = self.pending_events.lock().unwrap();
2686                 mem::swap(&mut ret, &mut *pending_events);
2687                 ret
2688         }
2689 }
2690
2691 impl ChainListener for ChannelManager {
2692         fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
2693                 let header_hash = header.bitcoin_hash();
2694                 log_trace!(self, "Block {} at height {} connected with {} txn matched", header_hash, height, txn_matched.len());
2695                 let _ = self.total_consistency_lock.read().unwrap();
2696                 let mut failed_channels = Vec::new();
2697                 {
2698                         let mut channel_lock = self.channel_state.lock().unwrap();
2699                         let channel_state = channel_lock.borrow_parts();
2700                         let short_to_id = channel_state.short_to_id;
2701                         let pending_msg_events = channel_state.pending_msg_events;
2702                         channel_state.by_id.retain(|_, channel| {
2703                                 let chan_res = channel.block_connected(header, height, txn_matched, indexes_of_txn_matched);
2704                                 if let Ok(Some(funding_locked)) = chan_res {
2705                                         pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2706                                                 node_id: channel.get_their_node_id(),
2707                                                 msg: funding_locked,
2708                                         });
2709                                         if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
2710                                                 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2711                                                         node_id: channel.get_their_node_id(),
2712                                                         msg: announcement_sigs,
2713                                                 });
2714                                         }
2715                                         short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
2716                                 } else if let Err(e) = chan_res {
2717                                         pending_msg_events.push(events::MessageSendEvent::HandleError {
2718                                                 node_id: channel.get_their_node_id(),
2719                                                 action: Some(msgs::ErrorAction::SendErrorMessage { msg: e }),
2720                                         });
2721                                         return false;
2722                                 }
2723                                 if let Some(funding_txo) = channel.get_funding_txo() {
2724                                         for tx in txn_matched {
2725                                                 for inp in tx.input.iter() {
2726                                                         if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
2727                                                                 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()));
2728                                                                 if let Some(short_id) = channel.get_short_channel_id() {
2729                                                                         short_to_id.remove(&short_id);
2730                                                                 }
2731                                                                 // It looks like our counterparty went on-chain. We go ahead and
2732                                                                 // broadcast our latest local state as well here, just in case its
2733                                                                 // some kind of SPV attack, though we expect these to be dropped.
2734                                                                 failed_channels.push(channel.force_shutdown());
2735                                                                 if let Ok(update) = self.get_channel_update(&channel) {
2736                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2737                                                                                 msg: update
2738                                                                         });
2739                                                                 }
2740                                                                 return false;
2741                                                         }
2742                                                 }
2743                                         }
2744                                 }
2745                                 if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height) {
2746                                         if let Some(short_id) = channel.get_short_channel_id() {
2747                                                 short_to_id.remove(&short_id);
2748                                         }
2749                                         failed_channels.push(channel.force_shutdown());
2750                                         // If would_broadcast_at_height() is true, the channel_monitor will broadcast
2751                                         // the latest local tx for us, so we should skip that here (it doesn't really
2752                                         // hurt anything, but does make tests a bit simpler).
2753                                         failed_channels.last_mut().unwrap().0 = Vec::new();
2754                                         if let Ok(update) = self.get_channel_update(&channel) {
2755                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2756                                                         msg: update
2757                                                 });
2758                                         }
2759                                         return false;
2760                                 }
2761                                 true
2762                         });
2763                 }
2764                 for failure in failed_channels.drain(..) {
2765                         self.finish_force_close_channel(failure);
2766                 }
2767                 self.latest_block_height.store(height as usize, Ordering::Release);
2768                 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header_hash;
2769         }
2770
2771         /// We force-close the channel without letting our counterparty participate in the shutdown
2772         fn block_disconnected(&self, header: &BlockHeader) {
2773                 let _ = self.total_consistency_lock.read().unwrap();
2774                 let mut failed_channels = Vec::new();
2775                 {
2776                         let mut channel_lock = self.channel_state.lock().unwrap();
2777                         let channel_state = channel_lock.borrow_parts();
2778                         let short_to_id = channel_state.short_to_id;
2779                         let pending_msg_events = channel_state.pending_msg_events;
2780                         channel_state.by_id.retain(|_,  v| {
2781                                 if v.block_disconnected(header) {
2782                                         if let Some(short_id) = v.get_short_channel_id() {
2783                                                 short_to_id.remove(&short_id);
2784                                         }
2785                                         failed_channels.push(v.force_shutdown());
2786                                         if let Ok(update) = self.get_channel_update(&v) {
2787                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2788                                                         msg: update
2789                                                 });
2790                                         }
2791                                         false
2792                                 } else {
2793                                         true
2794                                 }
2795                         });
2796                 }
2797                 for failure in failed_channels.drain(..) {
2798                         self.finish_force_close_channel(failure);
2799                 }
2800                 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
2801                 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
2802         }
2803 }
2804
2805 impl ChannelMessageHandler for ChannelManager {
2806         //TODO: Handle errors and close channel (or so)
2807         fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), HandleError> {
2808                 let _ = self.total_consistency_lock.read().unwrap();
2809                 handle_error!(self, self.internal_open_channel(their_node_id, msg), their_node_id)
2810         }
2811
2812         fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), HandleError> {
2813                 let _ = self.total_consistency_lock.read().unwrap();
2814                 handle_error!(self, self.internal_accept_channel(their_node_id, msg), their_node_id)
2815         }
2816
2817         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), HandleError> {
2818                 let _ = self.total_consistency_lock.read().unwrap();
2819                 handle_error!(self, self.internal_funding_created(their_node_id, msg), their_node_id)
2820         }
2821
2822         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), HandleError> {
2823                 let _ = self.total_consistency_lock.read().unwrap();
2824                 handle_error!(self, self.internal_funding_signed(their_node_id, msg), their_node_id)
2825         }
2826
2827         fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), HandleError> {
2828                 let _ = self.total_consistency_lock.read().unwrap();
2829                 handle_error!(self, self.internal_funding_locked(their_node_id, msg), their_node_id)
2830         }
2831
2832         fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), HandleError> {
2833                 let _ = self.total_consistency_lock.read().unwrap();
2834                 handle_error!(self, self.internal_shutdown(their_node_id, msg), their_node_id)
2835         }
2836
2837         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), HandleError> {
2838                 let _ = self.total_consistency_lock.read().unwrap();
2839                 handle_error!(self, self.internal_closing_signed(their_node_id, msg), their_node_id)
2840         }
2841
2842         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), msgs::HandleError> {
2843                 let _ = self.total_consistency_lock.read().unwrap();
2844                 handle_error!(self, self.internal_update_add_htlc(their_node_id, msg), their_node_id)
2845         }
2846
2847         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), HandleError> {
2848                 let _ = self.total_consistency_lock.read().unwrap();
2849                 handle_error!(self, self.internal_update_fulfill_htlc(their_node_id, msg), their_node_id)
2850         }
2851
2852         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), HandleError> {
2853                 let _ = self.total_consistency_lock.read().unwrap();
2854                 handle_error!(self, self.internal_update_fail_htlc(their_node_id, msg), their_node_id)
2855         }
2856
2857         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), HandleError> {
2858                 let _ = self.total_consistency_lock.read().unwrap();
2859                 handle_error!(self, self.internal_update_fail_malformed_htlc(their_node_id, msg), their_node_id)
2860         }
2861
2862         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), HandleError> {
2863                 let _ = self.total_consistency_lock.read().unwrap();
2864                 handle_error!(self, self.internal_commitment_signed(their_node_id, msg), their_node_id)
2865         }
2866
2867         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), HandleError> {
2868                 let _ = self.total_consistency_lock.read().unwrap();
2869                 handle_error!(self, self.internal_revoke_and_ack(their_node_id, msg), their_node_id)
2870         }
2871
2872         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), HandleError> {
2873                 let _ = self.total_consistency_lock.read().unwrap();
2874                 handle_error!(self, self.internal_update_fee(their_node_id, msg), their_node_id)
2875         }
2876
2877         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), HandleError> {
2878                 let _ = self.total_consistency_lock.read().unwrap();
2879                 handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
2880         }
2881
2882         fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), HandleError> {
2883                 let _ = self.total_consistency_lock.read().unwrap();
2884                 handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), their_node_id)
2885         }
2886
2887         fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
2888                 let _ = self.total_consistency_lock.read().unwrap();
2889                 let mut failed_channels = Vec::new();
2890                 let mut failed_payments = Vec::new();
2891                 {
2892                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2893                         let channel_state = channel_state_lock.borrow_parts();
2894                         let short_to_id = channel_state.short_to_id;
2895                         let pending_msg_events = channel_state.pending_msg_events;
2896                         if no_connection_possible {
2897                                 log_debug!(self, "Failing all channels with {} due to no_connection_possible", log_pubkey!(their_node_id));
2898                                 channel_state.by_id.retain(|_, chan| {
2899                                         if chan.get_their_node_id() == *their_node_id {
2900                                                 if let Some(short_id) = chan.get_short_channel_id() {
2901                                                         short_to_id.remove(&short_id);
2902                                                 }
2903                                                 failed_channels.push(chan.force_shutdown());
2904                                                 if let Ok(update) = self.get_channel_update(&chan) {
2905                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2906                                                                 msg: update
2907                                                         });
2908                                                 }
2909                                                 false
2910                                         } else {
2911                                                 true
2912                                         }
2913                                 });
2914                         } else {
2915                                 log_debug!(self, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(their_node_id));
2916                                 channel_state.by_id.retain(|_, chan| {
2917                                         if chan.get_their_node_id() == *their_node_id {
2918                                                 //TODO: mark channel disabled (and maybe announce such after a timeout).
2919                                                 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused();
2920                                                 if !failed_adds.is_empty() {
2921                                                         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
2922                                                         failed_payments.push((chan_update, failed_adds));
2923                                                 }
2924                                                 if chan.is_shutdown() {
2925                                                         if let Some(short_id) = chan.get_short_channel_id() {
2926                                                                 short_to_id.remove(&short_id);
2927                                                         }
2928                                                         return false;
2929                                                 }
2930                                         }
2931                                         true
2932                                 })
2933                         }
2934                 }
2935                 for failure in failed_channels.drain(..) {
2936                         self.finish_force_close_channel(failure);
2937                 }
2938                 for (chan_update, mut htlc_sources) in failed_payments {
2939                         for (htlc_source, payment_hash) in htlc_sources.drain(..) {
2940                                 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
2941                         }
2942                 }
2943         }
2944
2945         fn peer_connected(&self, their_node_id: &PublicKey) {
2946                 log_debug!(self, "Generating channel_reestablish events for {}", log_pubkey!(their_node_id));
2947
2948                 let _ = self.total_consistency_lock.read().unwrap();
2949                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2950                 let channel_state = channel_state_lock.borrow_parts();
2951                 let pending_msg_events = channel_state.pending_msg_events;
2952                 channel_state.by_id.retain(|_, chan| {
2953                         if chan.get_their_node_id() == *their_node_id {
2954                                 if !chan.have_received_message() {
2955                                         // If we created this (outbound) channel while we were disconnected from the
2956                                         // peer we probably failed to send the open_channel message, which is now
2957                                         // lost. We can't have had anything pending related to this channel, so we just
2958                                         // drop it.
2959                                         false
2960                                 } else {
2961                                         pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
2962                                                 node_id: chan.get_their_node_id(),
2963                                                 msg: chan.get_channel_reestablish(),
2964                                         });
2965                                         true
2966                                 }
2967                         } else { true }
2968                 });
2969                 //TODO: Also re-broadcast announcement_signatures
2970         }
2971
2972         fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
2973                 let _ = self.total_consistency_lock.read().unwrap();
2974
2975                 if msg.channel_id == [0; 32] {
2976                         for chan in self.list_channels() {
2977                                 if chan.remote_network_id == *their_node_id {
2978                                         self.force_close_channel(&chan.channel_id);
2979                                 }
2980                         }
2981                 } else {
2982                         self.force_close_channel(&msg.channel_id);
2983                 }
2984         }
2985 }
2986
2987 const SERIALIZATION_VERSION: u8 = 1;
2988 const MIN_SERIALIZATION_VERSION: u8 = 1;
2989
2990 impl Writeable for PendingForwardHTLCInfo {
2991         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2992                 if let &Some(ref onion) = &self.onion_packet {
2993                         1u8.write(writer)?;
2994                         onion.write(writer)?;
2995                 } else {
2996                         0u8.write(writer)?;
2997                 }
2998                 self.incoming_shared_secret.write(writer)?;
2999                 self.payment_hash.write(writer)?;
3000                 self.short_channel_id.write(writer)?;
3001                 self.amt_to_forward.write(writer)?;
3002                 self.outgoing_cltv_value.write(writer)?;
3003                 Ok(())
3004         }
3005 }
3006
3007 impl<R: ::std::io::Read> Readable<R> for PendingForwardHTLCInfo {
3008         fn read(reader: &mut R) -> Result<PendingForwardHTLCInfo, DecodeError> {
3009                 let onion_packet = match <u8 as Readable<R>>::read(reader)? {
3010                         0 => None,
3011                         1 => Some(msgs::OnionPacket::read(reader)?),
3012                         _ => return Err(DecodeError::InvalidValue),
3013                 };
3014                 Ok(PendingForwardHTLCInfo {
3015                         onion_packet,
3016                         incoming_shared_secret: Readable::read(reader)?,
3017                         payment_hash: Readable::read(reader)?,
3018                         short_channel_id: Readable::read(reader)?,
3019                         amt_to_forward: Readable::read(reader)?,
3020                         outgoing_cltv_value: Readable::read(reader)?,
3021                 })
3022         }
3023 }
3024
3025 impl Writeable for HTLCFailureMsg {
3026         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3027                 match self {
3028                         &HTLCFailureMsg::Relay(ref fail_msg) => {
3029                                 0u8.write(writer)?;
3030                                 fail_msg.write(writer)?;
3031                         },
3032                         &HTLCFailureMsg::Malformed(ref fail_msg) => {
3033                                 1u8.write(writer)?;
3034                                 fail_msg.write(writer)?;
3035                         }
3036                 }
3037                 Ok(())
3038         }
3039 }
3040
3041 impl<R: ::std::io::Read> Readable<R> for HTLCFailureMsg {
3042         fn read(reader: &mut R) -> Result<HTLCFailureMsg, DecodeError> {
3043                 match <u8 as Readable<R>>::read(reader)? {
3044                         0 => Ok(HTLCFailureMsg::Relay(Readable::read(reader)?)),
3045                         1 => Ok(HTLCFailureMsg::Malformed(Readable::read(reader)?)),
3046                         _ => Err(DecodeError::InvalidValue),
3047                 }
3048         }
3049 }
3050
3051 impl Writeable for PendingHTLCStatus {
3052         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3053                 match self {
3054                         &PendingHTLCStatus::Forward(ref forward_info) => {
3055                                 0u8.write(writer)?;
3056                                 forward_info.write(writer)?;
3057                         },
3058                         &PendingHTLCStatus::Fail(ref fail_msg) => {
3059                                 1u8.write(writer)?;
3060                                 fail_msg.write(writer)?;
3061                         }
3062                 }
3063                 Ok(())
3064         }
3065 }
3066
3067 impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
3068         fn read(reader: &mut R) -> Result<PendingHTLCStatus, DecodeError> {
3069                 match <u8 as Readable<R>>::read(reader)? {
3070                         0 => Ok(PendingHTLCStatus::Forward(Readable::read(reader)?)),
3071                         1 => Ok(PendingHTLCStatus::Fail(Readable::read(reader)?)),
3072                         _ => Err(DecodeError::InvalidValue),
3073                 }
3074         }
3075 }
3076
3077 impl_writeable!(HTLCPreviousHopData, 0, {
3078         short_channel_id,
3079         htlc_id,
3080         incoming_packet_shared_secret
3081 });
3082
3083 impl Writeable for HTLCSource {
3084         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3085                 match self {
3086                         &HTLCSource::PreviousHopData(ref hop_data) => {
3087                                 0u8.write(writer)?;
3088                                 hop_data.write(writer)?;
3089                         },
3090                         &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } => {
3091                                 1u8.write(writer)?;
3092                                 route.write(writer)?;
3093                                 session_priv.write(writer)?;
3094                                 first_hop_htlc_msat.write(writer)?;
3095                         }
3096                 }
3097                 Ok(())
3098         }
3099 }
3100
3101 impl<R: ::std::io::Read> Readable<R> for HTLCSource {
3102         fn read(reader: &mut R) -> Result<HTLCSource, DecodeError> {
3103                 match <u8 as Readable<R>>::read(reader)? {
3104                         0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
3105                         1 => Ok(HTLCSource::OutboundRoute {
3106                                 route: Readable::read(reader)?,
3107                                 session_priv: Readable::read(reader)?,
3108                                 first_hop_htlc_msat: Readable::read(reader)?,
3109                         }),
3110                         _ => Err(DecodeError::InvalidValue),
3111                 }
3112         }
3113 }
3114
3115 impl Writeable for HTLCFailReason {
3116         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3117                 match self {
3118                         &HTLCFailReason::ErrorPacket { ref err } => {
3119                                 0u8.write(writer)?;
3120                                 err.write(writer)?;
3121                         },
3122                         &HTLCFailReason::Reason { ref failure_code, ref data } => {
3123                                 1u8.write(writer)?;
3124                                 failure_code.write(writer)?;
3125                                 data.write(writer)?;
3126                         }
3127                 }
3128                 Ok(())
3129         }
3130 }
3131
3132 impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
3133         fn read(reader: &mut R) -> Result<HTLCFailReason, DecodeError> {
3134                 match <u8 as Readable<R>>::read(reader)? {
3135                         0 => Ok(HTLCFailReason::ErrorPacket { err: Readable::read(reader)? }),
3136                         1 => Ok(HTLCFailReason::Reason {
3137                                 failure_code: Readable::read(reader)?,
3138                                 data: Readable::read(reader)?,
3139                         }),
3140                         _ => Err(DecodeError::InvalidValue),
3141                 }
3142         }
3143 }
3144
3145 impl_writeable!(HTLCForwardInfo, 0, {
3146         prev_short_channel_id,
3147         prev_htlc_id,
3148         forward_info
3149 });
3150
3151 impl Writeable for ChannelManager {
3152         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3153                 let _ = self.total_consistency_lock.write().unwrap();
3154
3155                 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
3156                 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
3157
3158                 self.genesis_hash.write(writer)?;
3159                 (self.latest_block_height.load(Ordering::Acquire) as u32).write(writer)?;
3160                 self.last_block_hash.lock().unwrap().write(writer)?;
3161
3162                 let channel_state = self.channel_state.lock().unwrap();
3163                 let mut unfunded_channels = 0;
3164                 for (_, channel) in channel_state.by_id.iter() {
3165                         if !channel.is_funding_initiated() {
3166                                 unfunded_channels += 1;
3167                         }
3168                 }
3169                 ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
3170                 for (_, channel) in channel_state.by_id.iter() {
3171                         if channel.is_funding_initiated() {
3172                                 channel.write(writer)?;
3173                         }
3174                 }
3175
3176                 (channel_state.forward_htlcs.len() as u64).write(writer)?;
3177                 for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
3178                         short_channel_id.write(writer)?;
3179                         (pending_forwards.len() as u64).write(writer)?;
3180                         for forward in pending_forwards {
3181                                 forward.write(writer)?;
3182                         }
3183                 }
3184
3185                 (channel_state.claimable_htlcs.len() as u64).write(writer)?;
3186                 for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
3187                         payment_hash.write(writer)?;
3188                         (previous_hops.len() as u64).write(writer)?;
3189                         for previous_hop in previous_hops {
3190                                 previous_hop.write(writer)?;
3191                         }
3192                 }
3193
3194                 Ok(())
3195         }
3196 }
3197
3198 /// Arguments for the creation of a ChannelManager that are not deserialized.
3199 ///
3200 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
3201 /// is:
3202 /// 1) Deserialize all stored ChannelMonitors.
3203 /// 2) Deserialize the ChannelManager by filling in this struct and calling <(Sha256dHash,
3204 ///    ChannelManager)>::read(reader, args).
3205 ///    This may result in closing some Channels if the ChannelMonitor is newer than the stored
3206 ///    ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
3207 /// 3) Register all relevant ChannelMonitor outpoints with your chain watch mechanism using
3208 ///    ChannelMonitor::get_monitored_outpoints and ChannelMonitor::get_funding_txo().
3209 /// 4) Reconnect blocks on your ChannelMonitors.
3210 /// 5) Move the ChannelMonitors into your local ManyChannelMonitor.
3211 /// 6) Disconnect/connect blocks on the ChannelManager.
3212 /// 7) Register the new ChannelManager with your ChainWatchInterface (this does not happen
3213 ///    automatically as it does in ChannelManager::new()).
3214 pub struct ChannelManagerReadArgs<'a> {
3215         /// The keys provider which will give us relevant keys. Some keys will be loaded during
3216         /// deserialization.
3217         pub keys_manager: Arc<KeysInterface>,
3218
3219         /// The fee_estimator for use in the ChannelManager in the future.
3220         ///
3221         /// No calls to the FeeEstimator will be made during deserialization.
3222         pub fee_estimator: Arc<FeeEstimator>,
3223         /// The ManyChannelMonitor for use in the ChannelManager in the future.
3224         ///
3225         /// No calls to the ManyChannelMonitor will be made during deserialization. It is assumed that
3226         /// you have deserialized ChannelMonitors separately and will add them to your
3227         /// ManyChannelMonitor after deserializing this ChannelManager.
3228         pub monitor: Arc<ManyChannelMonitor>,
3229         /// The ChainWatchInterface for use in the ChannelManager in the future.
3230         ///
3231         /// No calls to the ChainWatchInterface will be made during deserialization.
3232         pub chain_monitor: Arc<ChainWatchInterface>,
3233         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
3234         /// used to broadcast the latest local commitment transactions of channels which must be
3235         /// force-closed during deserialization.
3236         pub tx_broadcaster: Arc<BroadcasterInterface>,
3237         /// The Logger for use in the ChannelManager and which may be used to log information during
3238         /// deserialization.
3239         pub logger: Arc<Logger>,
3240         /// Default settings used for new channels. Any existing channels will continue to use the
3241         /// runtime settings which were stored when the ChannelManager was serialized.
3242         pub default_config: UserConfig,
3243
3244         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
3245         /// value.get_funding_txo() should be the key).
3246         ///
3247         /// If a monitor is inconsistent with the channel state during deserialization the channel will
3248         /// be force-closed using the data in the channelmonitor and the Channel will be dropped. This
3249         /// is true for missing channels as well. If there is a monitor missing for which we find
3250         /// channel data Err(DecodeError::InvalidValue) will be returned.
3251         ///
3252         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
3253         /// this struct.
3254         pub channel_monitors: &'a HashMap<OutPoint, &'a ChannelMonitor>,
3255 }
3256
3257 impl<'a, R : ::std::io::Read> ReadableArgs<R, ChannelManagerReadArgs<'a>> for (Sha256dHash, ChannelManager) {
3258         fn read(reader: &mut R, args: ChannelManagerReadArgs<'a>) -> Result<Self, DecodeError> {
3259                 let _ver: u8 = Readable::read(reader)?;
3260                 let min_ver: u8 = Readable::read(reader)?;
3261                 if min_ver > SERIALIZATION_VERSION {
3262                         return Err(DecodeError::UnknownVersion);
3263                 }
3264
3265                 let genesis_hash: Sha256dHash = Readable::read(reader)?;
3266                 let latest_block_height: u32 = Readable::read(reader)?;
3267                 let last_block_hash: Sha256dHash = Readable::read(reader)?;
3268
3269                 let mut closed_channels = Vec::new();
3270
3271                 let channel_count: u64 = Readable::read(reader)?;
3272                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
3273                 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3274                 let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3275                 for _ in 0..channel_count {
3276                         let mut channel: Channel = ReadableArgs::read(reader, args.logger.clone())?;
3277                         if channel.last_block_connected != last_block_hash {
3278                                 return Err(DecodeError::InvalidValue);
3279                         }
3280
3281                         let funding_txo = channel.channel_monitor().get_funding_txo().ok_or(DecodeError::InvalidValue)?;
3282                         funding_txo_set.insert(funding_txo.clone());
3283                         if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
3284                                 if channel.get_cur_local_commitment_transaction_number() != monitor.get_cur_local_commitment_number() ||
3285                                                 channel.get_revoked_remote_commitment_transaction_number() != monitor.get_min_seen_secret() ||
3286                                                 channel.get_cur_remote_commitment_transaction_number() != monitor.get_cur_remote_commitment_number() {
3287                                         let mut force_close_res = channel.force_shutdown();
3288                                         force_close_res.0 = monitor.get_latest_local_commitment_txn();
3289                                         closed_channels.push(force_close_res);
3290                                 } else {
3291                                         if let Some(short_channel_id) = channel.get_short_channel_id() {
3292                                                 short_to_id.insert(short_channel_id, channel.channel_id());
3293                                         }
3294                                         by_id.insert(channel.channel_id(), channel);
3295                                 }
3296                         } else {
3297                                 return Err(DecodeError::InvalidValue);
3298                         }
3299                 }
3300
3301                 for (ref funding_txo, ref monitor) in args.channel_monitors.iter() {
3302                         if !funding_txo_set.contains(funding_txo) {
3303                                 closed_channels.push((monitor.get_latest_local_commitment_txn(), Vec::new()));
3304                         }
3305                 }
3306
3307                 let forward_htlcs_count: u64 = Readable::read(reader)?;
3308                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
3309                 for _ in 0..forward_htlcs_count {
3310                         let short_channel_id = Readable::read(reader)?;
3311                         let pending_forwards_count: u64 = Readable::read(reader)?;
3312                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, 128));
3313                         for _ in 0..pending_forwards_count {
3314                                 pending_forwards.push(Readable::read(reader)?);
3315                         }
3316                         forward_htlcs.insert(short_channel_id, pending_forwards);
3317                 }
3318
3319                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
3320                 let mut claimable_htlcs = HashMap::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
3321                 for _ in 0..claimable_htlcs_count {
3322                         let payment_hash = Readable::read(reader)?;
3323                         let previous_hops_len: u64 = Readable::read(reader)?;
3324                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, 2));
3325                         for _ in 0..previous_hops_len {
3326                                 previous_hops.push(Readable::read(reader)?);
3327                         }
3328                         claimable_htlcs.insert(payment_hash, previous_hops);
3329                 }
3330
3331                 let channel_manager = ChannelManager {
3332                         genesis_hash,
3333                         fee_estimator: args.fee_estimator,
3334                         monitor: args.monitor,
3335                         chain_monitor: args.chain_monitor,
3336                         tx_broadcaster: args.tx_broadcaster,
3337
3338                         latest_block_height: AtomicUsize::new(latest_block_height as usize),
3339                         last_block_hash: Mutex::new(last_block_hash),
3340                         secp_ctx: Secp256k1::new(),
3341
3342                         channel_state: Mutex::new(ChannelHolder {
3343                                 by_id,
3344                                 short_to_id,
3345                                 next_forward: Instant::now(),
3346                                 forward_htlcs,
3347                                 claimable_htlcs,
3348                                 pending_msg_events: Vec::new(),
3349                         }),
3350                         our_network_key: args.keys_manager.get_node_secret(),
3351
3352                         pending_events: Mutex::new(Vec::new()),
3353                         total_consistency_lock: RwLock::new(()),
3354                         keys_manager: args.keys_manager,
3355                         logger: args.logger,
3356                         default_configuration: args.default_config,
3357                 };
3358
3359                 for close_res in closed_channels.drain(..) {
3360                         channel_manager.finish_force_close_channel(close_res);
3361                         //TODO: Broadcast channel update for closed channels, but only after we've made a
3362                         //connection or two.
3363                 }
3364
3365                 Ok((last_block_hash.clone(), channel_manager))
3366         }
3367 }
3368
3369 #[cfg(test)]
3370 mod tests {
3371         use chain::chaininterface;
3372         use chain::transaction::OutPoint;
3373         use chain::chaininterface::{ChainListener, ChainWatchInterface};
3374         use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor};
3375         use chain::keysinterface;
3376         use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
3377         use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,OnionKeys,PaymentFailReason,RAACommitmentOrder, PaymentPreimage, PaymentHash};
3378         use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, ManyChannelMonitor};
3379         use ln::channel::{ACCEPTED_HTLC_SCRIPT_WEIGHT, OFFERED_HTLC_SCRIPT_WEIGHT};
3380         use ln::router::{Route, RouteHop, Router};
3381         use ln::msgs;
3382         use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler};
3383         use util::test_utils;
3384         use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
3385         use util::errors::APIError;
3386         use util::logger::Logger;
3387         use util::ser::{Writeable, Writer, ReadableArgs};
3388         use util::config::UserConfig;
3389
3390         use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
3391         use bitcoin::util::bip143;
3392         use bitcoin::util::address::Address;
3393         use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
3394         use bitcoin::blockdata::block::{Block, BlockHeader};
3395         use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType};
3396         use bitcoin::blockdata::script::{Builder, Script};
3397         use bitcoin::blockdata::opcodes;
3398         use bitcoin::blockdata::constants::genesis_block;
3399         use bitcoin::network::constants::Network;
3400
3401         use hex;
3402
3403         use secp256k1::{Secp256k1, Message};
3404         use secp256k1::key::{PublicKey,SecretKey};
3405
3406         use crypto::sha2::Sha256;
3407         use crypto::digest::Digest;
3408
3409         use rand::{thread_rng,Rng};
3410
3411         use std::cell::RefCell;
3412         use std::collections::{BTreeSet, HashMap, HashSet};
3413         use std::default::Default;
3414         use std::rc::Rc;
3415         use std::sync::{Arc, Mutex};
3416         use std::sync::atomic::Ordering;
3417         use std::time::Instant;
3418         use std::mem;
3419
3420         fn build_test_onion_keys() -> Vec<OnionKeys> {
3421                 // Keys from BOLT 4, used in both test vector tests
3422                 let secp_ctx = Secp256k1::new();
3423
3424                 let route = Route {
3425                         hops: vec!(
3426                                         RouteHop {
3427                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
3428                                                 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
3429                                         },
3430                                         RouteHop {
3431                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
3432                                                 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
3433                                         },
3434                                         RouteHop {
3435                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
3436                                                 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
3437                                         },
3438                                         RouteHop {
3439                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..]).unwrap(),
3440                                                 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
3441                                         },
3442                                         RouteHop {
3443                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145").unwrap()[..]).unwrap(),
3444                                                 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
3445                                         },
3446                         ),
3447                 };
3448
3449                 let session_priv = SecretKey::from_slice(&secp_ctx, &hex::decode("4141414141414141414141414141414141414141414141414141414141414141").unwrap()[..]).unwrap();
3450
3451                 let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
3452                 assert_eq!(onion_keys.len(), route.hops.len());
3453                 onion_keys
3454         }
3455
3456         #[test]
3457         fn onion_vectors() {
3458                 // Packet creation test vectors from BOLT 4
3459                 let onion_keys = build_test_onion_keys();
3460
3461                 assert_eq!(onion_keys[0].shared_secret[..], hex::decode("53eb63ea8a3fec3b3cd433b85cd62a4b145e1dda09391b348c4e1cd36a03ea66").unwrap()[..]);
3462                 assert_eq!(onion_keys[0].blinding_factor[..], hex::decode("2ec2e5da605776054187180343287683aa6a51b4b1c04d6dd49c45d8cffb3c36").unwrap()[..]);
3463                 assert_eq!(onion_keys[0].ephemeral_pubkey.serialize()[..], hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]);
3464                 assert_eq!(onion_keys[0].rho, hex::decode("ce496ec94def95aadd4bec15cdb41a740c9f2b62347c4917325fcc6fb0453986").unwrap()[..]);
3465                 assert_eq!(onion_keys[0].mu, hex::decode("b57061dc6d0a2b9f261ac410c8b26d64ac5506cbba30267a649c28c179400eba").unwrap()[..]);
3466
3467                 assert_eq!(onion_keys[1].shared_secret[..], hex::decode("a6519e98832a0b179f62123b3567c106db99ee37bef036e783263602f3488fae").unwrap()[..]);
3468                 assert_eq!(onion_keys[1].blinding_factor[..], hex::decode("bf66c28bc22e598cfd574a1931a2bafbca09163df2261e6d0056b2610dab938f").unwrap()[..]);
3469                 assert_eq!(onion_keys[1].ephemeral_pubkey.serialize()[..], hex::decode("028f9438bfbf7feac2e108d677e3a82da596be706cc1cf342b75c7b7e22bf4e6e2").unwrap()[..]);
3470                 assert_eq!(onion_keys[1].rho, hex::decode("450ffcabc6449094918ebe13d4f03e433d20a3d28a768203337bc40b6e4b2c59").unwrap()[..]);
3471                 assert_eq!(onion_keys[1].mu, hex::decode("05ed2b4a3fb023c2ff5dd6ed4b9b6ea7383f5cfe9d59c11d121ec2c81ca2eea9").unwrap()[..]);
3472
3473                 assert_eq!(onion_keys[2].shared_secret[..], hex::decode("3a6b412548762f0dbccce5c7ae7bb8147d1caf9b5471c34120b30bc9c04891cc").unwrap()[..]);
3474                 assert_eq!(onion_keys[2].blinding_factor[..], hex::decode("a1f2dadd184eb1627049673f18c6325814384facdee5bfd935d9cb031a1698a5").unwrap()[..]);
3475                 assert_eq!(onion_keys[2].ephemeral_pubkey.serialize()[..], hex::decode("03bfd8225241ea71cd0843db7709f4c222f62ff2d4516fd38b39914ab6b83e0da0").unwrap()[..]);
3476                 assert_eq!(onion_keys[2].rho, hex::decode("11bf5c4f960239cb37833936aa3d02cea82c0f39fd35f566109c41f9eac8deea").unwrap()[..]);
3477                 assert_eq!(onion_keys[2].mu, hex::decode("caafe2820fa00eb2eeb78695ae452eba38f5a53ed6d53518c5c6edf76f3f5b78").unwrap()[..]);
3478
3479                 assert_eq!(onion_keys[3].shared_secret[..], hex::decode("21e13c2d7cfe7e18836df50872466117a295783ab8aab0e7ecc8c725503ad02d").unwrap()[..]);
3480                 assert_eq!(onion_keys[3].blinding_factor[..], hex::decode("7cfe0b699f35525029ae0fa437c69d0f20f7ed4e3916133f9cacbb13c82ff262").unwrap()[..]);
3481                 assert_eq!(onion_keys[3].ephemeral_pubkey.serialize()[..], hex::decode("031dde6926381289671300239ea8e57ffaf9bebd05b9a5b95beaf07af05cd43595").unwrap()[..]);
3482                 assert_eq!(onion_keys[3].rho, hex::decode("cbe784ab745c13ff5cffc2fbe3e84424aa0fd669b8ead4ee562901a4a4e89e9e").unwrap()[..]);
3483                 assert_eq!(onion_keys[3].mu, hex::decode("5052aa1b3d9f0655a0932e50d42f0c9ba0705142c25d225515c45f47c0036ee9").unwrap()[..]);
3484
3485                 assert_eq!(onion_keys[4].shared_secret[..], hex::decode("b5756b9b542727dbafc6765a49488b023a725d631af688fc031217e90770c328").unwrap()[..]);
3486                 assert_eq!(onion_keys[4].blinding_factor[..], hex::decode("c96e00dddaf57e7edcd4fb5954be5b65b09f17cb6d20651b4e90315be5779205").unwrap()[..]);
3487                 assert_eq!(onion_keys[4].ephemeral_pubkey.serialize()[..], hex::decode("03a214ebd875aab6ddfd77f22c5e7311d7f77f17a169e599f157bbcdae8bf071f4").unwrap()[..]);
3488                 assert_eq!(onion_keys[4].rho, hex::decode("034e18b8cc718e8af6339106e706c52d8df89e2b1f7e9142d996acf88df8799b").unwrap()[..]);
3489                 assert_eq!(onion_keys[4].mu, hex::decode("8e45e5c61c2b24cb6382444db6698727afb063adecd72aada233d4bf273d975a").unwrap()[..]);
3490
3491                 // Test vectors below are flat-out wrong: they claim to set outgoing_cltv_value to non-0 :/
3492                 let payloads = vec!(
3493                         msgs::OnionHopData {
3494                                 realm: 0,
3495                                 data: msgs::OnionRealm0HopData {
3496                                         short_channel_id: 0,
3497                                         amt_to_forward: 0,
3498                                         outgoing_cltv_value: 0,
3499                                 },
3500                                 hmac: [0; 32],
3501                         },
3502                         msgs::OnionHopData {
3503                                 realm: 0,
3504                                 data: msgs::OnionRealm0HopData {
3505                                         short_channel_id: 0x0101010101010101,
3506                                         amt_to_forward: 0x0100000001,
3507                                         outgoing_cltv_value: 0,
3508                                 },
3509                                 hmac: [0; 32],
3510                         },
3511                         msgs::OnionHopData {
3512                                 realm: 0,
3513                                 data: msgs::OnionRealm0HopData {
3514                                         short_channel_id: 0x0202020202020202,
3515                                         amt_to_forward: 0x0200000002,
3516                                         outgoing_cltv_value: 0,
3517                                 },
3518                                 hmac: [0; 32],
3519                         },
3520                         msgs::OnionHopData {
3521                                 realm: 0,
3522                                 data: msgs::OnionRealm0HopData {
3523                                         short_channel_id: 0x0303030303030303,
3524                                         amt_to_forward: 0x0300000003,
3525                                         outgoing_cltv_value: 0,
3526                                 },
3527                                 hmac: [0; 32],
3528                         },
3529                         msgs::OnionHopData {
3530                                 realm: 0,
3531                                 data: msgs::OnionRealm0HopData {
3532                                         short_channel_id: 0x0404040404040404,
3533                                         amt_to_forward: 0x0400000004,
3534                                         outgoing_cltv_value: 0,
3535                                 },
3536                                 hmac: [0; 32],
3537                         },
3538                 );
3539
3540                 let packet = ChannelManager::construct_onion_packet(payloads, onion_keys, &PaymentHash([0x42; 32]));
3541                 // Just check the final packet encoding, as it includes all the per-hop vectors in it
3542                 // anyway...
3543                 assert_eq!(packet.encode(), hex::decode("0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619e5f14350c2a76fc232b5e46d421e9615471ab9e0bc887beff8c95fdb878f7b3a716a996c7845c93d90e4ecbb9bde4ece2f69425c99e4bc820e44485455f135edc0d10f7d61ab590531cf08000179a333a347f8b4072f216400406bdf3bf038659793d4a1fd7b246979e3150a0a4cb052c9ec69acf0f48c3d39cd55675fe717cb7d80ce721caad69320c3a469a202f1e468c67eaf7a7cd8226d0fd32f7b48084dca885d56047694762b67021713ca673929c163ec36e04e40ca8e1c6d17569419d3039d9a1ec866abe044a9ad635778b961fc0776dc832b3a451bd5d35072d2269cf9b040f6b7a7dad84fb114ed413b1426cb96ceaf83825665ed5a1d002c1687f92465b49ed4c7f0218ff8c6c7dd7221d589c65b3b9aaa71a41484b122846c7c7b57e02e679ea8469b70e14fe4f70fee4d87b910cf144be6fe48eef24da475c0b0bcc6565ae82cd3f4e3b24c76eaa5616c6111343306ab35c1fe5ca4a77c0e314ed7dba39d6f1e0de791719c241a939cc493bea2bae1c1e932679ea94d29084278513c77b899cc98059d06a27d171b0dbdf6bee13ddc4fc17a0c4d2827d488436b57baa167544138ca2e64a11b43ac8a06cd0c2fba2d4d900ed2d9205305e2d7383cc98dacb078133de5f6fb6bed2ef26ba92cea28aafc3b9948dd9ae5559e8bd6920b8cea462aa445ca6a95e0e7ba52961b181c79e73bd581821df2b10173727a810c92b83b5ba4a0403eb710d2ca10689a35bec6c3a708e9e92f7d78ff3c5d9989574b00c6736f84c199256e76e19e78f0c98a9d580b4a658c84fc8f2096c2fbea8f5f8c59d0fdacb3be2802ef802abbecb3aba4acaac69a0e965abd8981e9896b1f6ef9d60f7a164b371af869fd0e48073742825e9434fc54da837e120266d53302954843538ea7c6c3dbfb4ff3b2fdbe244437f2a153ccf7bdb4c92aa08102d4f3cff2ae5ef86fab4653595e6a5837fa2f3e29f27a9cde5966843fb847a4a61f1e76c281fe8bb2b0a181d096100db5a1a5ce7a910238251a43ca556712eaadea167fb4d7d75825e440f3ecd782036d7574df8bceacb397abefc5f5254d2722215c53ff54af8299aaaad642c6d72a14d27882d9bbd539e1cc7a527526ba89b8c037ad09120e98ab042d3e8652b31ae0e478516bfaf88efca9f3676ffe99d2819dcaeb7610a626695f53117665d267d3f7abebd6bbd6733f645c72c389f03855bdf1e4b8075b516569b118233a0f0971d24b83113c0b096f5216a207ca99a7cddc81c130923fe3d91e7508c9ac5f2e914ff5dccab9e558566fa14efb34ac98d878580814b94b73acbfde9072f30b881f7f0fff42d4045d1ace6322d86a97d164aa84d93a60498065cc7c20e636f5862dc81531a88c60305a2e59a985be327a6902e4bed986dbf4a0b50c217af0ea7fdf9ab37f9ea1a1aaa72f54cf40154ea9b269f1a7c09f9f43245109431a175d50e2db0132337baa0ef97eed0fcf20489da36b79a1172faccc2f7ded7c60e00694282d93359c4682135642bc81f433574aa8ef0c97b4ade7ca372c5ffc23c7eddd839bab4e0f14d6df15c9dbeab176bec8b5701cf054eb3072f6dadc98f88819042bf10c407516ee58bce33fbe3b3d86a54255e577db4598e30a135361528c101683a5fcde7e8ba53f3456254be8f45fe3a56120ae96ea3773631fcb3873aa3abd91bcff00bd38bd43697a2e789e00da6077482e7b1b1a677b5afae4c54e6cbdf7377b694eb7d7a5b913476a5be923322d3de06060fd5e819635232a2cf4f0731da13b8546d1d6d4f8d75b9fce6c2341a71b0ea6f780df54bfdb0dd5cd9855179f602f9172307c7268724c3618e6817abd793adc214a0dc0bc616816632f27ea336fb56dfd").unwrap());
3544         }
3545
3546         #[test]
3547         fn test_failure_packet_onion() {
3548                 // Returning Errors test vectors from BOLT 4
3549
3550                 let onion_keys = build_test_onion_keys();
3551                 let onion_error = ChannelManager::build_failure_packet(&onion_keys[4].shared_secret[..], 0x2002, &[0; 0]);
3552                 assert_eq!(onion_error.encode(), hex::decode("4c2fc8bc08510334b6833ad9c3e79cd1b52ae59dfe5c2a4b23ead50f09f7ee0b0002200200fe0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap());
3553
3554                 let onion_packet_1 = ChannelManager::encrypt_failure_packet(&onion_keys[4].shared_secret[..], &onion_error.encode()[..]);
3555                 assert_eq!(onion_packet_1.data, hex::decode("a5e6bd0c74cb347f10cce367f949098f2457d14c046fd8a22cb96efb30b0fdcda8cb9168b50f2fd45edd73c1b0c8b33002df376801ff58aaa94000bf8a86f92620f343baef38a580102395ae3abf9128d1047a0736ff9b83d456740ebbb4aeb3aa9737f18fb4afb4aa074fb26c4d702f42968888550a3bded8c05247e045b866baef0499f079fdaeef6538f31d44deafffdfd3afa2fb4ca9082b8f1c465371a9894dd8c243fb4847e004f5256b3e90e2edde4c9fb3082ddfe4d1e734cacd96ef0706bf63c9984e22dc98851bcccd1c3494351feb458c9c6af41c0044bea3c47552b1d992ae542b17a2d0bba1a096c78d169034ecb55b6e3a7263c26017f033031228833c1daefc0dedb8cf7c3e37c9c37ebfe42f3225c326e8bcfd338804c145b16e34e4").unwrap());
3556
3557                 let onion_packet_2 = ChannelManager::encrypt_failure_packet(&onion_keys[3].shared_secret[..], &onion_packet_1.data[..]);
3558                 assert_eq!(onion_packet_2.data, hex::decode("c49a1ce81680f78f5f2000cda36268de34a3f0a0662f55b4e837c83a8773c22aa081bab1616a0011585323930fa5b9fae0c85770a2279ff59ec427ad1bbff9001c0cd1497004bd2a0f68b50704cf6d6a4bf3c8b6a0833399a24b3456961ba00736785112594f65b6b2d44d9f5ea4e49b5e1ec2af978cbe31c67114440ac51a62081df0ed46d4a3df295da0b0fe25c0115019f03f15ec86fabb4c852f83449e812f141a9395b3f70b766ebbd4ec2fae2b6955bd8f32684c15abfe8fd3a6261e52650e8807a92158d9f1463261a925e4bfba44bd20b166d532f0017185c3a6ac7957adefe45559e3072c8dc35abeba835a8cb01a71a15c736911126f27d46a36168ca5ef7dccd4e2886212602b181463e0dd30185c96348f9743a02aca8ec27c0b90dca270").unwrap());
3559
3560                 let onion_packet_3 = ChannelManager::encrypt_failure_packet(&onion_keys[2].shared_secret[..], &onion_packet_2.data[..]);
3561                 assert_eq!(onion_packet_3.data, hex::decode("a5d3e8634cfe78b2307d87c6d90be6fe7855b4f2cc9b1dfb19e92e4b79103f61ff9ac25f412ddfb7466e74f81b3e545563cdd8f5524dae873de61d7bdfccd496af2584930d2b566b4f8d3881f8c043df92224f38cf094cfc09d92655989531524593ec6d6caec1863bdfaa79229b5020acc034cd6deeea1021c50586947b9b8e6faa83b81fbfa6133c0af5d6b07c017f7158fa94f0d206baf12dda6b68f785b773b360fd0497e16cc402d779c8d48d0fa6315536ef0660f3f4e1865f5b38ea49c7da4fd959de4e83ff3ab686f059a45c65ba2af4a6a79166aa0f496bf04d06987b6d2ea205bdb0d347718b9aeff5b61dfff344993a275b79717cd815b6ad4c0beb568c4ac9c36ff1c315ec1119a1993c4b61e6eaa0375e0aaf738ac691abd3263bf937e3").unwrap());
3562
3563                 let onion_packet_4 = ChannelManager::encrypt_failure_packet(&onion_keys[1].shared_secret[..], &onion_packet_3.data[..]);
3564                 assert_eq!(onion_packet_4.data, hex::decode("aac3200c4968f56b21f53e5e374e3a2383ad2b1b6501bbcc45abc31e59b26881b7dfadbb56ec8dae8857add94e6702fb4c3a4de22e2e669e1ed926b04447fc73034bb730f4932acd62727b75348a648a1128744657ca6a4e713b9b646c3ca66cac02cdab44dd3439890ef3aaf61708714f7375349b8da541b2548d452d84de7084bb95b3ac2345201d624d31f4d52078aa0fa05a88b4e20202bd2b86ac5b52919ea305a8949de95e935eed0319cf3cf19ebea61d76ba92532497fcdc9411d06bcd4275094d0a4a3c5d3a945e43305a5a9256e333e1f64dbca5fcd4e03a39b9012d197506e06f29339dfee3331995b21615337ae060233d39befea925cc262873e0530408e6990f1cbd233a150ef7b004ff6166c70c68d9f8c853c1abca640b8660db2921").unwrap());
3565
3566                 let onion_packet_5 = ChannelManager::encrypt_failure_packet(&onion_keys[0].shared_secret[..], &onion_packet_4.data[..]);
3567                 assert_eq!(onion_packet_5.data, hex::decode("9c5add3963fc7f6ed7f148623c84134b5647e1306419dbe2174e523fa9e2fbed3a06a19f899145610741c83ad40b7712aefaddec8c6baf7325d92ea4ca4d1df8bce517f7e54554608bf2bd8071a4f52a7a2f7ffbb1413edad81eeea5785aa9d990f2865dc23b4bc3c301a94eec4eabebca66be5cf638f693ec256aec514620cc28ee4a94bd9565bc4d4962b9d3641d4278fb319ed2b84de5b665f307a2db0f7fbb757366067d88c50f7e829138fde4f78d39b5b5802f1b92a8a820865af5cc79f9f30bc3f461c66af95d13e5e1f0381c184572a91dee1c849048a647a1158cf884064deddbf1b0b88dfe2f791428d0ba0f6fb2f04e14081f69165ae66d9297c118f0907705c9c4954a199bae0bb96fad763d690e7daa6cfda59ba7f2c8d11448b604d12d").unwrap());
3568         }
3569
3570         fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
3571                 assert!(chain.does_match_tx(tx));
3572                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3573                 chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
3574                 for i in 2..100 {
3575                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3576                         chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
3577                 }
3578         }
3579
3580         struct Node {
3581                 chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
3582                 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
3583                 chan_monitor: Arc<test_utils::TestChannelMonitor>,
3584                 node: Arc<ChannelManager>,
3585                 router: Router,
3586                 node_seed: [u8; 32],
3587                 network_payment_count: Rc<RefCell<u8>>,
3588                 network_chan_count: Rc<RefCell<u32>>,
3589         }
3590         impl Drop for Node {
3591                 fn drop(&mut self) {
3592                         if !::std::thread::panicking() {
3593                                 // Check that we processed all pending events
3594                                 assert_eq!(self.node.get_and_clear_pending_msg_events().len(), 0);
3595                                 assert_eq!(self.node.get_and_clear_pending_events().len(), 0);
3596                                 assert_eq!(self.chan_monitor.added_monitors.lock().unwrap().len(), 0);
3597                         }
3598                 }
3599         }
3600
3601         fn create_chan_between_nodes(node_a: &Node, node_b: &Node) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3602                 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001)
3603         }
3604
3605         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) {
3606                 let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat);
3607                 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
3608                 (announcement, as_update, bs_update, channel_id, tx)
3609         }
3610
3611         macro_rules! get_revoke_commit_msgs {
3612                 ($node: expr, $node_id: expr) => {
3613                         {
3614                                 let events = $node.node.get_and_clear_pending_msg_events();
3615                                 assert_eq!(events.len(), 2);
3616                                 (match events[0] {
3617                                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3618                                                 assert_eq!(*node_id, $node_id);
3619                                                 (*msg).clone()
3620                                         },
3621                                         _ => panic!("Unexpected event"),
3622                                 }, match events[1] {
3623                                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3624                                                 assert_eq!(*node_id, $node_id);
3625                                                 assert!(updates.update_add_htlcs.is_empty());
3626                                                 assert!(updates.update_fulfill_htlcs.is_empty());
3627                                                 assert!(updates.update_fail_htlcs.is_empty());
3628                                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
3629                                                 assert!(updates.update_fee.is_none());
3630                                                 updates.commitment_signed.clone()
3631                                         },
3632                                         _ => panic!("Unexpected event"),
3633                                 })
3634                         }
3635                 }
3636         }
3637
3638         macro_rules! get_event_msg {
3639                 ($node: expr, $event_type: path, $node_id: expr) => {
3640                         {
3641                                 let events = $node.node.get_and_clear_pending_msg_events();
3642                                 assert_eq!(events.len(), 1);
3643                                 match events[0] {
3644                                         $event_type { ref node_id, ref msg } => {
3645                                                 assert_eq!(*node_id, $node_id);
3646                                                 (*msg).clone()
3647                                         },
3648                                         _ => panic!("Unexpected event"),
3649                                 }
3650                         }
3651                 }
3652         }
3653
3654         macro_rules! get_htlc_update_msgs {
3655                 ($node: expr, $node_id: expr) => {
3656                         {
3657                                 let events = $node.node.get_and_clear_pending_msg_events();
3658                                 assert_eq!(events.len(), 1);
3659                                 match events[0] {
3660                                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3661                                                 assert_eq!(*node_id, $node_id);
3662                                                 (*updates).clone()
3663                                         },
3664                                         _ => panic!("Unexpected event"),
3665                                 }
3666                         }
3667                 }
3668         }
3669
3670         macro_rules! get_feerate {
3671                 ($node: expr, $channel_id: expr) => {
3672                         {
3673                                 let chan_lock = $node.node.channel_state.lock().unwrap();
3674                                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
3675                                 chan.get_feerate()
3676                         }
3677                 }
3678         }
3679
3680
3681         fn create_chan_between_nodes_with_value_init(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> Transaction {
3682                 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
3683                 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();
3684                 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();
3685
3686                 let chan_id = *node_a.network_chan_count.borrow();
3687                 let tx;
3688                 let funding_output;
3689
3690                 let events_2 = node_a.node.get_and_clear_pending_events();
3691                 assert_eq!(events_2.len(), 1);
3692                 match events_2[0] {
3693                         Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
3694                                 assert_eq!(*channel_value_satoshis, channel_value);
3695                                 assert_eq!(user_channel_id, 42);
3696
3697                                 tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
3698                                         value: *channel_value_satoshis, script_pubkey: output_script.clone(),
3699                                 }]};
3700                                 funding_output = OutPoint::new(tx.txid(), 0);
3701
3702                                 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
3703                                 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3704                                 assert_eq!(added_monitors.len(), 1);
3705                                 assert_eq!(added_monitors[0].0, funding_output);
3706                                 added_monitors.clear();
3707                         },
3708                         _ => panic!("Unexpected event"),
3709                 }
3710
3711                 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();
3712                 {
3713                         let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
3714                         assert_eq!(added_monitors.len(), 1);
3715                         assert_eq!(added_monitors[0].0, funding_output);
3716                         added_monitors.clear();
3717                 }
3718
3719                 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();
3720                 {
3721                         let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3722                         assert_eq!(added_monitors.len(), 1);
3723                         assert_eq!(added_monitors[0].0, funding_output);
3724                         added_monitors.clear();
3725                 }
3726
3727                 let events_4 = node_a.node.get_and_clear_pending_events();
3728                 assert_eq!(events_4.len(), 1);
3729                 match events_4[0] {
3730                         Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
3731                                 assert_eq!(user_channel_id, 42);
3732                                 assert_eq!(*funding_txo, funding_output);
3733                         },
3734                         _ => panic!("Unexpected event"),
3735                 };
3736
3737                 tx
3738         }
3739
3740         fn create_chan_between_nodes_with_value_confirm(node_a: &Node, node_b: &Node, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
3741                 confirm_transaction(&node_b.chain_monitor, &tx, tx.version);
3742                 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();
3743
3744                 let channel_id;
3745
3746                 confirm_transaction(&node_a.chain_monitor, &tx, tx.version);
3747                 let events_6 = node_a.node.get_and_clear_pending_msg_events();
3748                 assert_eq!(events_6.len(), 2);
3749                 ((match events_6[0] {
3750                         MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3751                                 channel_id = msg.channel_id.clone();
3752                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
3753                                 msg.clone()
3754                         },
3755                         _ => panic!("Unexpected event"),
3756                 }, match events_6[1] {
3757                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3758                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
3759                                 msg.clone()
3760                         },
3761                         _ => panic!("Unexpected event"),
3762                 }), channel_id)
3763         }
3764
3765         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) {
3766                 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat);
3767                 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
3768                 (msgs, chan_id, tx)
3769         }
3770
3771         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) {
3772                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0).unwrap();
3773                 let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
3774                 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1).unwrap();
3775
3776                 let events_7 = node_b.node.get_and_clear_pending_msg_events();
3777                 assert_eq!(events_7.len(), 1);
3778                 let (announcement, bs_update) = match events_7[0] {
3779                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3780                                 (msg, update_msg)
3781                         },
3782                         _ => panic!("Unexpected event"),
3783                 };
3784
3785                 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs).unwrap();
3786                 let events_8 = node_a.node.get_and_clear_pending_msg_events();
3787                 assert_eq!(events_8.len(), 1);
3788                 let as_update = match events_8[0] {
3789                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3790                                 assert!(*announcement == *msg);
3791                                 update_msg
3792                         },
3793                         _ => panic!("Unexpected event"),
3794                 };
3795
3796                 *node_a.network_chan_count.borrow_mut() += 1;
3797
3798                 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
3799         }
3800
3801         fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3802                 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001)
3803         }
3804
3805         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) {
3806                 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat);
3807                 for node in nodes {
3808                         assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
3809                         node.router.handle_channel_update(&chan_announcement.1).unwrap();
3810                         node.router.handle_channel_update(&chan_announcement.2).unwrap();
3811                 }
3812                 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
3813         }
3814
3815         macro_rules! check_spends {
3816                 ($tx: expr, $spends_tx: expr) => {
3817                         {
3818                                 let mut funding_tx_map = HashMap::new();
3819                                 let spends_tx = $spends_tx;
3820                                 funding_tx_map.insert(spends_tx.txid(), spends_tx);
3821                                 $tx.verify(&funding_tx_map).unwrap();
3822                         }
3823                 }
3824         }
3825
3826         macro_rules! get_closing_signed_broadcast {
3827                 ($node: expr, $dest_pubkey: expr) => {
3828                         {
3829                                 let events = $node.get_and_clear_pending_msg_events();
3830                                 assert!(events.len() == 1 || events.len() == 2);
3831                                 (match events[events.len() - 1] {
3832                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
3833                                                 assert_eq!(msg.contents.flags & 2, 2);
3834                                                 msg.clone()
3835                                         },
3836                                         _ => panic!("Unexpected event"),
3837                                 }, if events.len() == 2 {
3838                                         match events[0] {
3839                                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3840                                                         assert_eq!(*node_id, $dest_pubkey);
3841                                                         Some(msg.clone())
3842                                                 },
3843                                                 _ => panic!("Unexpected event"),
3844                                         }
3845                                 } else { None })
3846                         }
3847                 }
3848         }
3849
3850         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) {
3851                 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) };
3852                 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
3853                 let (tx_a, tx_b);
3854
3855                 node_a.close_channel(channel_id).unwrap();
3856                 node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id())).unwrap();
3857
3858                 let events_1 = node_b.get_and_clear_pending_msg_events();
3859                 assert!(events_1.len() >= 1);
3860                 let shutdown_b = match events_1[0] {
3861                         MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
3862                                 assert_eq!(node_id, &node_a.get_our_node_id());
3863                                 msg.clone()
3864                         },
3865                         _ => panic!("Unexpected event"),
3866                 };
3867
3868                 let closing_signed_b = if !close_inbound_first {
3869                         assert_eq!(events_1.len(), 1);
3870                         None
3871                 } else {
3872                         Some(match events_1[1] {
3873                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3874                                         assert_eq!(node_id, &node_a.get_our_node_id());
3875                                         msg.clone()
3876                                 },
3877                                 _ => panic!("Unexpected event"),
3878                         })
3879                 };
3880
3881                 node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b).unwrap();
3882                 let (as_update, bs_update) = if close_inbound_first {
3883                         assert!(node_a.get_and_clear_pending_msg_events().is_empty());
3884                         node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3885                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3886                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3887                         let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3888
3889                         node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
3890                         let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3891                         assert!(none_b.is_none());
3892                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3893                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3894                         (as_update, bs_update)
3895                 } else {
3896                         let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
3897
3898                         node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a).unwrap();
3899                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3900                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3901                         let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3902
3903                         node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3904                         let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3905                         assert!(none_a.is_none());
3906                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3907                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3908                         (as_update, bs_update)
3909                 };
3910                 assert_eq!(tx_a, tx_b);
3911                 check_spends!(tx_a, funding_tx);
3912
3913                 (as_update, bs_update, tx_a)
3914         }
3915
3916         struct SendEvent {
3917                 node_id: PublicKey,
3918                 msgs: Vec<msgs::UpdateAddHTLC>,
3919                 commitment_msg: msgs::CommitmentSigned,
3920         }
3921         impl SendEvent {
3922                 fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
3923                         assert!(updates.update_fulfill_htlcs.is_empty());
3924                         assert!(updates.update_fail_htlcs.is_empty());
3925                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3926                         assert!(updates.update_fee.is_none());
3927                         SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
3928                 }
3929
3930                 fn from_event(event: MessageSendEvent) -> SendEvent {
3931                         match event {
3932                                 MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
3933                                 _ => panic!("Unexpected event type!"),
3934                         }
3935                 }
3936
3937                 fn from_node(node: &Node) -> SendEvent {
3938                         let mut events = node.node.get_and_clear_pending_msg_events();
3939                         assert_eq!(events.len(), 1);
3940                         SendEvent::from_event(events.pop().unwrap())
3941                 }
3942         }
3943
3944         macro_rules! check_added_monitors {
3945                 ($node: expr, $count: expr) => {
3946                         {
3947                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
3948                                 assert_eq!(added_monitors.len(), $count);
3949                                 added_monitors.clear();
3950                         }
3951                 }
3952         }
3953
3954         macro_rules! commitment_signed_dance {
3955                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
3956                         {
3957                                 check_added_monitors!($node_a, 0);
3958                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3959                                 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3960                                 check_added_monitors!($node_a, 1);
3961                                 commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
3962                         }
3963                 };
3964                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
3965                         {
3966                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
3967                                 check_added_monitors!($node_b, 0);
3968                                 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3969                                 $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
3970                                 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3971                                 check_added_monitors!($node_b, 1);
3972                                 $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed).unwrap();
3973                                 let (bs_revoke_and_ack, extra_msg_option) = {
3974                                         let events = $node_b.node.get_and_clear_pending_msg_events();
3975                                         assert!(events.len() <= 2);
3976                                         (match events[0] {
3977                                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3978                                                         assert_eq!(*node_id, $node_a.node.get_our_node_id());
3979                                                         (*msg).clone()
3980                                                 },
3981                                                 _ => panic!("Unexpected event"),
3982                                         }, events.get(1).map(|e| e.clone()))
3983                                 };
3984                                 check_added_monitors!($node_b, 1);
3985                                 if $fail_backwards {
3986                                         assert!($node_a.node.get_and_clear_pending_events().is_empty());
3987                                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3988                                 }
3989                                 (extra_msg_option, bs_revoke_and_ack)
3990                         }
3991                 };
3992                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
3993                         {
3994                                 check_added_monitors!($node_a, 0);
3995                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3996                                 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3997                                 check_added_monitors!($node_a, 1);
3998                                 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
3999                                 assert!(extra_msg_option.is_none());
4000                                 bs_revoke_and_ack
4001                         }
4002                 };
4003                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
4004                         {
4005                                 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
4006                                 $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
4007                                 {
4008                                         let mut added_monitors = $node_a.chan_monitor.added_monitors.lock().unwrap();
4009                                         if $fail_backwards {
4010                                                 assert_eq!(added_monitors.len(), 2);
4011                                                 assert!(added_monitors[0].0 != added_monitors[1].0);
4012                                         } else {
4013                                                 assert_eq!(added_monitors.len(), 1);
4014                                         }
4015                                         added_monitors.clear();
4016                                 }
4017                                 extra_msg_option
4018                         }
4019                 };
4020                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
4021                         {
4022                                 assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
4023                         }
4024                 };
4025                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
4026                         {
4027                                 commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
4028                                 if $fail_backwards {
4029                                         let channel_state = $node_a.node.channel_state.lock().unwrap();
4030                                         assert_eq!(channel_state.pending_msg_events.len(), 1);
4031                                         if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
4032                                                 assert_ne!(*node_id, $node_b.node.get_our_node_id());
4033                                         } else { panic!("Unexpected event"); }
4034                                 } else {
4035                                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
4036                                 }
4037                         }
4038                 }
4039         }
4040
4041         macro_rules! get_payment_preimage_hash {
4042                 ($node: expr) => {
4043                         {
4044                                 let payment_preimage = PaymentPreimage([*$node.network_payment_count.borrow(); 32]);
4045                                 *$node.network_payment_count.borrow_mut() += 1;
4046                                 let mut payment_hash = PaymentHash([0; 32]);
4047                                 let mut sha = Sha256::new();
4048                                 sha.input(&payment_preimage.0[..]);
4049                                 sha.result(&mut payment_hash.0[..]);
4050                                 (payment_preimage, payment_hash)
4051                         }
4052                 }
4053         }
4054
4055         fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
4056                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4057
4058                 let mut payment_event = {
4059                         origin_node.node.send_payment(route, our_payment_hash).unwrap();
4060                         check_added_monitors!(origin_node, 1);
4061
4062                         let mut events = origin_node.node.get_and_clear_pending_msg_events();
4063                         assert_eq!(events.len(), 1);
4064                         SendEvent::from_event(events.remove(0))
4065                 };
4066                 let mut prev_node = origin_node;
4067
4068                 for (idx, &node) in expected_route.iter().enumerate() {
4069                         assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
4070
4071                         node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4072                         check_added_monitors!(node, 0);
4073                         commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
4074
4075                         let events_1 = node.node.get_and_clear_pending_events();
4076                         assert_eq!(events_1.len(), 1);
4077                         match events_1[0] {
4078                                 Event::PendingHTLCsForwardable { .. } => { },
4079                                 _ => panic!("Unexpected event"),
4080                         };
4081
4082                         node.node.channel_state.lock().unwrap().next_forward = Instant::now();
4083                         node.node.process_pending_htlc_forwards();
4084
4085                         if idx == expected_route.len() - 1 {
4086                                 let events_2 = node.node.get_and_clear_pending_events();
4087                                 assert_eq!(events_2.len(), 1);
4088                                 match events_2[0] {
4089                                         Event::PaymentReceived { ref payment_hash, amt } => {
4090                                                 assert_eq!(our_payment_hash, *payment_hash);
4091                                                 assert_eq!(amt, recv_value);
4092                                         },
4093                                         _ => panic!("Unexpected event"),
4094                                 }
4095                         } else {
4096                                 let mut events_2 = node.node.get_and_clear_pending_msg_events();
4097                                 assert_eq!(events_2.len(), 1);
4098                                 check_added_monitors!(node, 1);
4099                                 payment_event = SendEvent::from_event(events_2.remove(0));
4100                                 assert_eq!(payment_event.msgs.len(), 1);
4101                         }
4102
4103                         prev_node = node;
4104                 }
4105
4106                 (our_payment_preimage, our_payment_hash)
4107         }
4108
4109         fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: PaymentPreimage) {
4110                 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
4111                 check_added_monitors!(expected_route.last().unwrap(), 1);
4112
4113                 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
4114                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4115                 macro_rules! get_next_msgs {
4116                         ($node: expr) => {
4117                                 {
4118                                         let events = $node.node.get_and_clear_pending_msg_events();
4119                                         assert_eq!(events.len(), 1);
4120                                         match events[0] {
4121                                                 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 } } => {
4122                                                         assert!(update_add_htlcs.is_empty());
4123                                                         assert_eq!(update_fulfill_htlcs.len(), 1);
4124                                                         assert!(update_fail_htlcs.is_empty());
4125                                                         assert!(update_fail_malformed_htlcs.is_empty());
4126                                                         assert!(update_fee.is_none());
4127                                                         expected_next_node = node_id.clone();
4128                                                         Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()))
4129                                                 },
4130                                                 _ => panic!("Unexpected event"),
4131                                         }
4132                                 }
4133                         }
4134                 }
4135
4136                 macro_rules! last_update_fulfill_dance {
4137                         ($node: expr, $prev_node: expr) => {
4138                                 {
4139                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4140                                         check_added_monitors!($node, 0);
4141                                         assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4142                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4143                                 }
4144                         }
4145                 }
4146                 macro_rules! mid_update_fulfill_dance {
4147                         ($node: expr, $prev_node: expr, $new_msgs: expr) => {
4148                                 {
4149                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4150                                         check_added_monitors!($node, 1);
4151                                         let new_next_msgs = if $new_msgs {
4152                                                 get_next_msgs!($node)
4153                                         } else {
4154                                                 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4155                                                 None
4156                                         };
4157                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4158                                         next_msgs = new_next_msgs;
4159                                 }
4160                         }
4161                 }
4162
4163                 let mut prev_node = expected_route.last().unwrap();
4164                 for (idx, node) in expected_route.iter().rev().enumerate() {
4165                         assert_eq!(expected_next_node, node.node.get_our_node_id());
4166                         let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
4167                         if next_msgs.is_some() {
4168                                 mid_update_fulfill_dance!(node, prev_node, update_next_msgs);
4169                         } else if update_next_msgs {
4170                                 next_msgs = get_next_msgs!(node);
4171                         } else {
4172                                 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
4173                         }
4174                         if !skip_last && idx == expected_route.len() - 1 {
4175                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4176                         }
4177
4178                         prev_node = node;
4179                 }
4180
4181                 if !skip_last {
4182                         last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
4183                         let events = origin_node.node.get_and_clear_pending_events();
4184                         assert_eq!(events.len(), 1);
4185                         match events[0] {
4186                                 Event::PaymentSent { payment_preimage } => {
4187                                         assert_eq!(payment_preimage, our_payment_preimage);
4188                                 },
4189                                 _ => panic!("Unexpected event"),
4190                         }
4191                 }
4192         }
4193
4194         fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: PaymentPreimage) {
4195                 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage);
4196         }
4197
4198         const TEST_FINAL_CLTV: u32 = 32;
4199
4200         fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
4201                 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();
4202                 assert_eq!(route.hops.len(), expected_route.len());
4203                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4204                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
4205                 }
4206
4207                 send_along_route(origin_node, route, expected_route, recv_value)
4208         }
4209
4210         fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
4211                 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();
4212                 assert_eq!(route.hops.len(), expected_route.len());
4213                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4214                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
4215                 }
4216
4217                 let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4218
4219                 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
4220                 match err {
4221                         APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
4222                         _ => panic!("Unknown error variants"),
4223                 };
4224         }
4225
4226         fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
4227                 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
4228                 claim_payment(&origin, expected_route, our_payment_preimage);
4229         }
4230
4231         fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: PaymentHash) {
4232                 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash, PaymentFailReason::PreimageUnknown));
4233                 check_added_monitors!(expected_route.last().unwrap(), 1);
4234
4235                 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
4236                 macro_rules! update_fail_dance {
4237                         ($node: expr, $prev_node: expr, $last_node: expr) => {
4238                                 {
4239                                         $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4240                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
4241                                 }
4242                         }
4243                 }
4244
4245                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4246                 let mut prev_node = expected_route.last().unwrap();
4247                 for (idx, node) in expected_route.iter().rev().enumerate() {
4248                         assert_eq!(expected_next_node, node.node.get_our_node_id());
4249                         if next_msgs.is_some() {
4250                                 // We may be the "last node" for the purpose of the commitment dance if we're
4251                                 // skipping the last node (implying it is disconnected) and we're the
4252                                 // second-to-last node!
4253                                 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
4254                         }
4255
4256                         let events = node.node.get_and_clear_pending_msg_events();
4257                         if !skip_last || idx != expected_route.len() - 1 {
4258                                 assert_eq!(events.len(), 1);
4259                                 match events[0] {
4260                                         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 } } => {
4261                                                 assert!(update_add_htlcs.is_empty());
4262                                                 assert!(update_fulfill_htlcs.is_empty());
4263                                                 assert_eq!(update_fail_htlcs.len(), 1);
4264                                                 assert!(update_fail_malformed_htlcs.is_empty());
4265                                                 assert!(update_fee.is_none());
4266                                                 expected_next_node = node_id.clone();
4267                                                 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
4268                                         },
4269                                         _ => panic!("Unexpected event"),
4270                                 }
4271                         } else {
4272                                 assert!(events.is_empty());
4273                         }
4274                         if !skip_last && idx == expected_route.len() - 1 {
4275                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4276                         }
4277
4278                         prev_node = node;
4279                 }
4280
4281                 if !skip_last {
4282                         update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
4283
4284                         let events = origin_node.node.get_and_clear_pending_events();
4285                         assert_eq!(events.len(), 1);
4286                         match events[0] {
4287                                 Event::PaymentFailed { payment_hash, rejected_by_dest } => {
4288                                         assert_eq!(payment_hash, our_payment_hash);
4289                                         assert!(rejected_by_dest);
4290                                 },
4291                                 _ => panic!("Unexpected event"),
4292                         }
4293                 }
4294         }
4295
4296         fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: PaymentHash) {
4297                 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
4298         }
4299
4300         fn create_network(node_count: usize) -> Vec<Node> {
4301                 let mut nodes = Vec::new();
4302                 let mut rng = thread_rng();
4303                 let secp_ctx = Secp256k1::new();
4304
4305                 let chan_count = Rc::new(RefCell::new(0));
4306                 let payment_count = Rc::new(RefCell::new(0));
4307
4308                 for i in 0..node_count {
4309                         let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
4310                         let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
4311                         let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
4312                         let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
4313                         let mut seed = [0; 32];
4314                         rng.fill_bytes(&mut seed);
4315                         let keys_manager = Arc::new(keysinterface::KeysManager::new(&seed, Network::Testnet, Arc::clone(&logger)));
4316                         let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone()));
4317                         let mut config = UserConfig::new();
4318                         config.channel_options.announced_channel = true;
4319                         config.channel_limits.force_announced_channel_preference = false;
4320                         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();
4321                         let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), chain_monitor.clone(), Arc::clone(&logger));
4322                         nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router, node_seed: seed,
4323                                 network_payment_count: payment_count.clone(),
4324                                 network_chan_count: chan_count.clone(),
4325                         });
4326                 }
4327
4328                 nodes
4329         }
4330
4331         #[test]
4332         fn test_async_inbound_update_fee() {
4333                 let mut nodes = create_network(2);
4334                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4335                 let channel_id = chan.2;
4336
4337                 // balancing
4338                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4339
4340                 // A                                        B
4341                 // update_fee                            ->
4342                 // send (1) commitment_signed            -.
4343                 //                                       <- update_add_htlc/commitment_signed
4344                 // send (2) RAA (awaiting remote revoke) -.
4345                 // (1) commitment_signed is delivered    ->
4346                 //                                       .- send (3) RAA (awaiting remote revoke)
4347                 // (2) RAA is delivered                  ->
4348                 //                                       .- send (4) commitment_signed
4349                 //                                       <- (3) RAA is delivered
4350                 // send (5) commitment_signed            -.
4351                 //                                       <- (4) commitment_signed is delivered
4352                 // send (6) RAA                          -.
4353                 // (5) commitment_signed is delivered    ->
4354                 //                                       <- RAA
4355                 // (6) RAA is delivered                  ->
4356
4357                 // First nodes[0] generates an update_fee
4358                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4359                 check_added_monitors!(nodes[0], 1);
4360
4361                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4362                 assert_eq!(events_0.len(), 1);
4363                 let (update_msg, commitment_signed) = match events_0[0] { // (1)
4364                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4365                                 (update_fee.as_ref(), commitment_signed)
4366                         },
4367                         _ => panic!("Unexpected event"),
4368                 };
4369
4370                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4371
4372                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4373                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4374                 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();
4375                 check_added_monitors!(nodes[1], 1);
4376
4377                 let payment_event = {
4378                         let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4379                         assert_eq!(events_1.len(), 1);
4380                         SendEvent::from_event(events_1.remove(0))
4381                 };
4382                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4383                 assert_eq!(payment_event.msgs.len(), 1);
4384
4385                 // ...now when the messages get delivered everyone should be happy
4386                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4387                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4388                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4389                 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4390                 check_added_monitors!(nodes[0], 1);
4391
4392                 // deliver(1), generate (3):
4393                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4394                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4395                 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
4396                 check_added_monitors!(nodes[1], 1);
4397
4398                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap(); // deliver (2)
4399                 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4400                 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
4401                 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
4402                 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
4403                 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
4404                 assert!(bs_update.update_fee.is_none()); // (4)
4405                 check_added_monitors!(nodes[1], 1);
4406
4407                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap(); // deliver (3)
4408                 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4409                 assert!(as_update.update_add_htlcs.is_empty()); // (5)
4410                 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
4411                 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
4412                 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
4413                 assert!(as_update.update_fee.is_none()); // (5)
4414                 check_added_monitors!(nodes[0], 1);
4415
4416                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed).unwrap(); // deliver (4)
4417                 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4418                 // only (6) so get_event_msg's assert(len == 1) passes
4419                 check_added_monitors!(nodes[0], 1);
4420
4421                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed).unwrap(); // deliver (5)
4422                 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4423                 check_added_monitors!(nodes[1], 1);
4424
4425                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4426                 check_added_monitors!(nodes[0], 1);
4427
4428                 let events_2 = nodes[0].node.get_and_clear_pending_events();
4429                 assert_eq!(events_2.len(), 1);
4430                 match events_2[0] {
4431                         Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
4432                         _ => panic!("Unexpected event"),
4433                 }
4434
4435                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap(); // deliver (6)
4436                 check_added_monitors!(nodes[1], 1);
4437         }
4438
4439         #[test]
4440         fn test_update_fee_unordered_raa() {
4441                 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
4442                 // crash in an earlier version of the update_fee patch)
4443                 let mut nodes = create_network(2);
4444                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4445                 let channel_id = chan.2;
4446
4447                 // balancing
4448                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4449
4450                 // First nodes[0] generates an update_fee
4451                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4452                 check_added_monitors!(nodes[0], 1);
4453
4454                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4455                 assert_eq!(events_0.len(), 1);
4456                 let update_msg = match events_0[0] { // (1)
4457                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
4458                                 update_fee.as_ref()
4459                         },
4460                         _ => panic!("Unexpected event"),
4461                 };
4462
4463                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4464
4465                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4466                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4467                 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();
4468                 check_added_monitors!(nodes[1], 1);
4469
4470                 let payment_event = {
4471                         let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4472                         assert_eq!(events_1.len(), 1);
4473                         SendEvent::from_event(events_1.remove(0))
4474                 };
4475                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4476                 assert_eq!(payment_event.msgs.len(), 1);
4477
4478                 // ...now when the messages get delivered everyone should be happy
4479                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4480                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4481                 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4482                 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4483                 check_added_monitors!(nodes[0], 1);
4484
4485                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap(); // deliver (2)
4486                 check_added_monitors!(nodes[1], 1);
4487
4488                 // We can't continue, sadly, because our (1) now has a bogus signature
4489         }
4490
4491         #[test]
4492         fn test_multi_flight_update_fee() {
4493                 let nodes = create_network(2);
4494                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4495                 let channel_id = chan.2;
4496
4497                 // A                                        B
4498                 // update_fee/commitment_signed          ->
4499                 //                                       .- send (1) RAA and (2) commitment_signed
4500                 // update_fee (never committed)          ->
4501                 // (3) update_fee                        ->
4502                 // We have to manually generate the above update_fee, it is allowed by the protocol but we
4503                 // don't track which updates correspond to which revoke_and_ack responses so we're in
4504                 // AwaitingRAA mode and will not generate the update_fee yet.
4505                 //                                       <- (1) RAA delivered
4506                 // (3) is generated and send (4) CS      -.
4507                 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
4508                 // know the per_commitment_point to use for it.
4509                 //                                       <- (2) commitment_signed delivered
4510                 // revoke_and_ack                        ->
4511                 //                                          B should send no response here
4512                 // (4) commitment_signed delivered       ->
4513                 //                                       <- RAA/commitment_signed delivered
4514                 // revoke_and_ack                        ->
4515
4516                 // First nodes[0] generates an update_fee
4517                 let initial_feerate = get_feerate!(nodes[0], channel_id);
4518                 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
4519                 check_added_monitors!(nodes[0], 1);
4520
4521                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4522                 assert_eq!(events_0.len(), 1);
4523                 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
4524                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4525                                 (update_fee.as_ref().unwrap(), commitment_signed)
4526                         },
4527                         _ => panic!("Unexpected event"),
4528                 };
4529
4530                 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
4531                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1).unwrap();
4532                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1).unwrap();
4533                 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4534                 check_added_monitors!(nodes[1], 1);
4535
4536                 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
4537                 // transaction:
4538                 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
4539                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4540                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4541
4542                 // Create the (3) update_fee message that nodes[0] will generate before it does...
4543                 let mut update_msg_2 = msgs::UpdateFee {
4544                         channel_id: update_msg_1.channel_id.clone(),
4545                         feerate_per_kw: (initial_feerate + 30) as u32,
4546                 };
4547
4548                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4549
4550                 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
4551                 // Deliver (3)
4552                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4553
4554                 // Deliver (1), generating (3) and (4)
4555                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap();
4556                 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4557                 check_added_monitors!(nodes[0], 1);
4558                 assert!(as_second_update.update_add_htlcs.is_empty());
4559                 assert!(as_second_update.update_fulfill_htlcs.is_empty());
4560                 assert!(as_second_update.update_fail_htlcs.is_empty());
4561                 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
4562                 // Check that the update_fee newly generated matches what we delivered:
4563                 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
4564                 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
4565
4566                 // Deliver (2) commitment_signed
4567                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
4568                 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4569                 check_added_monitors!(nodes[0], 1);
4570                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4571
4572                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap();
4573                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4574                 check_added_monitors!(nodes[1], 1);
4575
4576                 // Delever (4)
4577                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed).unwrap();
4578                 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4579                 check_added_monitors!(nodes[1], 1);
4580
4581                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4582                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4583                 check_added_monitors!(nodes[0], 1);
4584
4585                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment).unwrap();
4586                 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4587                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4588                 check_added_monitors!(nodes[0], 1);
4589
4590                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap();
4591                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4592                 check_added_monitors!(nodes[1], 1);
4593         }
4594
4595         #[test]
4596         fn test_update_fee_vanilla() {
4597                 let nodes = create_network(2);
4598                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4599                 let channel_id = chan.2;
4600
4601                 let feerate = get_feerate!(nodes[0], channel_id);
4602                 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
4603                 check_added_monitors!(nodes[0], 1);
4604
4605                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4606                 assert_eq!(events_0.len(), 1);
4607                 let (update_msg, commitment_signed) = match events_0[0] {
4608                                 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 } } => {
4609                                 (update_fee.as_ref(), commitment_signed)
4610                         },
4611                         _ => panic!("Unexpected event"),
4612                 };
4613                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4614
4615                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4616                 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4617                 check_added_monitors!(nodes[1], 1);
4618
4619                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4620                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4621                 check_added_monitors!(nodes[0], 1);
4622
4623                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4624                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4625                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4626                 check_added_monitors!(nodes[0], 1);
4627
4628                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4629                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4630                 check_added_monitors!(nodes[1], 1);
4631         }
4632
4633         #[test]
4634         fn test_update_fee_that_funder_cannot_afford() {
4635                 let nodes = create_network(2);
4636                 let channel_value = 1888;
4637                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000);
4638                 let channel_id = chan.2;
4639
4640                 let feerate = 260;
4641                 nodes[0].node.update_fee(channel_id, feerate).unwrap();
4642                 check_added_monitors!(nodes[0], 1);
4643                 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4644
4645                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap()).unwrap();
4646
4647                 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
4648
4649                 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
4650                 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
4651                 {
4652                         let chan_lock = nodes[1].node.channel_state.lock().unwrap();
4653                         let chan = chan_lock.by_id.get(&channel_id).unwrap();
4654
4655                         //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
4656                         let num_htlcs = chan.last_local_commitment_txn[0].output.len() - 2;
4657                         let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
4658                         let mut actual_fee = chan.last_local_commitment_txn[0].output.iter().fold(0, |acc, output| acc + output.value);
4659                         actual_fee = channel_value - actual_fee;
4660                         assert_eq!(total_fee, actual_fee);
4661                 } //drop the mutex
4662
4663                 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
4664                 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
4665                 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
4666                 check_added_monitors!(nodes[0], 1);
4667
4668                 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4669
4670                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap()).unwrap();
4671
4672                 //While producing the commitment_signed response after handling a received update_fee request the
4673                 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
4674                 //Should produce and error.
4675                 let err = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed).unwrap_err();
4676
4677                 assert!(match err.err {
4678                         "Funding remote cannot afford proposed new fee" => true,
4679                         _ => false,
4680                 });
4681
4682                 //clear the message we could not handle
4683                 nodes[1].node.get_and_clear_pending_msg_events();
4684         }
4685
4686         #[test]
4687         fn test_update_fee_with_fundee_update_add_htlc() {
4688                 let mut nodes = create_network(2);
4689                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4690                 let channel_id = chan.2;
4691
4692                 // balancing
4693                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4694
4695                 let feerate = get_feerate!(nodes[0], channel_id);
4696                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4697                 check_added_monitors!(nodes[0], 1);
4698
4699                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4700                 assert_eq!(events_0.len(), 1);
4701                 let (update_msg, commitment_signed) = match events_0[0] {
4702                                 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 } } => {
4703                                 (update_fee.as_ref(), commitment_signed)
4704                         },
4705                         _ => panic!("Unexpected event"),
4706                 };
4707                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4708                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4709                 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4710                 check_added_monitors!(nodes[1], 1);
4711
4712                 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
4713
4714                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
4715
4716                 // nothing happens since node[1] is in AwaitingRemoteRevoke
4717                 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
4718                 {
4719                         let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
4720                         assert_eq!(added_monitors.len(), 0);
4721                         added_monitors.clear();
4722                 }
4723                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4724                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4725                 // node[1] has nothing to do
4726
4727                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4728                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4729                 check_added_monitors!(nodes[0], 1);
4730
4731                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4732                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4733                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4734                 check_added_monitors!(nodes[0], 1);
4735                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4736                 check_added_monitors!(nodes[1], 1);
4737                 // AwaitingRemoteRevoke ends here
4738
4739                 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4740                 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
4741                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
4742                 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
4743                 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
4744                 assert_eq!(commitment_update.update_fee.is_none(), true);
4745
4746                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]).unwrap();
4747                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4748                 check_added_monitors!(nodes[0], 1);
4749                 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4750
4751                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke).unwrap();
4752                 check_added_monitors!(nodes[1], 1);
4753                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4754
4755                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed).unwrap();
4756                 check_added_monitors!(nodes[1], 1);
4757                 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4758                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4759
4760                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke).unwrap();
4761                 check_added_monitors!(nodes[0], 1);
4762                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4763
4764                 let events = nodes[0].node.get_and_clear_pending_events();
4765                 assert_eq!(events.len(), 1);
4766                 match events[0] {
4767                         Event::PendingHTLCsForwardable { .. } => { },
4768                         _ => panic!("Unexpected event"),
4769                 };
4770                 nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
4771                 nodes[0].node.process_pending_htlc_forwards();
4772
4773                 let events = nodes[0].node.get_and_clear_pending_events();
4774                 assert_eq!(events.len(), 1);
4775                 match events[0] {
4776                         Event::PaymentReceived { .. } => { },
4777                         _ => panic!("Unexpected event"),
4778                 };
4779
4780                 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
4781
4782                 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
4783                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
4784                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4785         }
4786
4787         #[test]
4788         fn test_update_fee() {
4789                 let nodes = create_network(2);
4790                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4791                 let channel_id = chan.2;
4792
4793                 // A                                        B
4794                 // (1) update_fee/commitment_signed      ->
4795                 //                                       <- (2) revoke_and_ack
4796                 //                                       .- send (3) commitment_signed
4797                 // (4) update_fee/commitment_signed      ->
4798                 //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
4799                 //                                       <- (3) commitment_signed delivered
4800                 // send (6) revoke_and_ack               -.
4801                 //                                       <- (5) deliver revoke_and_ack
4802                 // (6) deliver revoke_and_ack            ->
4803                 //                                       .- send (7) commitment_signed in response to (4)
4804                 //                                       <- (7) deliver commitment_signed
4805                 // revoke_and_ack                        ->
4806
4807                 // Create and deliver (1)...
4808                 let feerate = get_feerate!(nodes[0], channel_id);
4809                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4810                 check_added_monitors!(nodes[0], 1);
4811
4812                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4813                 assert_eq!(events_0.len(), 1);
4814                 let (update_msg, commitment_signed) = match events_0[0] {
4815                                 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 } } => {
4816                                 (update_fee.as_ref(), commitment_signed)
4817                         },
4818                         _ => panic!("Unexpected event"),
4819                 };
4820                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4821
4822                 // Generate (2) and (3):
4823                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4824                 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4825                 check_added_monitors!(nodes[1], 1);
4826
4827                 // Deliver (2):
4828                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4829                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4830                 check_added_monitors!(nodes[0], 1);
4831
4832                 // Create and deliver (4)...
4833                 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
4834                 check_added_monitors!(nodes[0], 1);
4835                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4836                 assert_eq!(events_0.len(), 1);
4837                 let (update_msg, commitment_signed) = match events_0[0] {
4838                                 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 } } => {
4839                                 (update_fee.as_ref(), commitment_signed)
4840                         },
4841                         _ => panic!("Unexpected event"),
4842                 };
4843
4844                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4845                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4846                 check_added_monitors!(nodes[1], 1);
4847                 // ... creating (5)
4848                 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4849                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4850
4851                 // Handle (3), creating (6):
4852                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0).unwrap();
4853                 check_added_monitors!(nodes[0], 1);
4854                 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4855                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4856
4857                 // Deliver (5):
4858                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4859                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4860                 check_added_monitors!(nodes[0], 1);
4861
4862                 // Deliver (6), creating (7):
4863                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0).unwrap();
4864                 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4865                 assert!(commitment_update.update_add_htlcs.is_empty());
4866                 assert!(commitment_update.update_fulfill_htlcs.is_empty());
4867                 assert!(commitment_update.update_fail_htlcs.is_empty());
4868                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
4869                 assert!(commitment_update.update_fee.is_none());
4870                 check_added_monitors!(nodes[1], 1);
4871
4872                 // Deliver (7)
4873                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4874                 check_added_monitors!(nodes[0], 1);
4875                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4876                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4877
4878                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4879                 check_added_monitors!(nodes[1], 1);
4880                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4881
4882                 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
4883                 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
4884                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4885         }
4886
4887         #[test]
4888         fn pre_funding_lock_shutdown_test() {
4889                 // Test sending a shutdown prior to funding_locked after funding generation
4890                 let nodes = create_network(2);
4891                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0);
4892                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4893                 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4894                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4895
4896                 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
4897                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4898                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4899                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4900                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4901
4902                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4903                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4904                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4905                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4906                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4907                 assert!(node_0_none.is_none());
4908
4909                 assert!(nodes[0].node.list_channels().is_empty());
4910                 assert!(nodes[1].node.list_channels().is_empty());
4911         }
4912
4913         #[test]
4914         fn updates_shutdown_wait() {
4915                 // Test sending a shutdown with outstanding updates pending
4916                 let mut nodes = create_network(3);
4917                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4918                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4919                 let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4920                 let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4921
4922                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
4923
4924                 nodes[0].node.close_channel(&chan_1.2).unwrap();
4925                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4926                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4927                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4928                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4929
4930                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4931                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4932
4933                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4934                 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route_1, payment_hash) {}
4935                 else { panic!("New sends should fail!") };
4936                 if let Err(APIError::ChannelUnavailable {..}) = nodes[1].node.send_payment(route_2, payment_hash) {}
4937                 else { panic!("New sends should fail!") };
4938
4939                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
4940                 check_added_monitors!(nodes[2], 1);
4941                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4942                 assert!(updates.update_add_htlcs.is_empty());
4943                 assert!(updates.update_fail_htlcs.is_empty());
4944                 assert!(updates.update_fail_malformed_htlcs.is_empty());
4945                 assert!(updates.update_fee.is_none());
4946                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4947                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
4948                 check_added_monitors!(nodes[1], 1);
4949                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4950                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
4951
4952                 assert!(updates_2.update_add_htlcs.is_empty());
4953                 assert!(updates_2.update_fail_htlcs.is_empty());
4954                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
4955                 assert!(updates_2.update_fee.is_none());
4956                 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
4957                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
4958                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
4959
4960                 let events = nodes[0].node.get_and_clear_pending_events();
4961                 assert_eq!(events.len(), 1);
4962                 match events[0] {
4963                         Event::PaymentSent { ref payment_preimage } => {
4964                                 assert_eq!(our_payment_preimage, *payment_preimage);
4965                         },
4966                         _ => panic!("Unexpected event"),
4967                 }
4968
4969                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4970                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4971                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4972                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4973                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4974                 assert!(node_0_none.is_none());
4975
4976                 assert!(nodes[0].node.list_channels().is_empty());
4977
4978                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4979                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
4980                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
4981                 assert!(nodes[1].node.list_channels().is_empty());
4982                 assert!(nodes[2].node.list_channels().is_empty());
4983         }
4984
4985         #[test]
4986         fn htlc_fail_async_shutdown() {
4987                 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
4988                 let mut nodes = create_network(3);
4989                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4990                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4991
4992                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4993                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4994                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
4995                 check_added_monitors!(nodes[0], 1);
4996                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4997                 assert_eq!(updates.update_add_htlcs.len(), 1);
4998                 assert!(updates.update_fulfill_htlcs.is_empty());
4999                 assert!(updates.update_fail_htlcs.is_empty());
5000                 assert!(updates.update_fail_malformed_htlcs.is_empty());
5001                 assert!(updates.update_fee.is_none());
5002
5003                 nodes[1].node.close_channel(&chan_1.2).unwrap();
5004                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5005                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
5006                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5007
5008                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5009                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
5010                 check_added_monitors!(nodes[1], 1);
5011                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
5012                 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
5013
5014                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5015                 assert!(updates_2.update_add_htlcs.is_empty());
5016                 assert!(updates_2.update_fulfill_htlcs.is_empty());
5017                 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
5018                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
5019                 assert!(updates_2.update_fee.is_none());
5020
5021                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]).unwrap();
5022                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
5023
5024                 let events = nodes[0].node.get_and_clear_pending_events();
5025                 assert_eq!(events.len(), 1);
5026                 match events[0] {
5027                         Event::PaymentFailed { ref payment_hash, ref rejected_by_dest } => {
5028                                 assert_eq!(our_payment_hash, *payment_hash);
5029                                 assert!(!rejected_by_dest);
5030                         },
5031                         _ => panic!("Unexpected event"),
5032                 }
5033
5034                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5035                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5036                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5037                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5038                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5039                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5040                 assert!(node_0_none.is_none());
5041
5042                 assert!(nodes[0].node.list_channels().is_empty());
5043
5044                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5045                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5046                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5047                 assert!(nodes[1].node.list_channels().is_empty());
5048                 assert!(nodes[2].node.list_channels().is_empty());
5049         }
5050
5051         fn do_test_shutdown_rebroadcast(recv_count: u8) {
5052                 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
5053                 // messages delivered prior to disconnect
5054                 let nodes = create_network(3);
5055                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5056                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5057
5058                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
5059
5060                 nodes[1].node.close_channel(&chan_1.2).unwrap();
5061                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5062                 if recv_count > 0 {
5063                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
5064                         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5065                         if recv_count > 1 {
5066                                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
5067                         }
5068                 }
5069
5070                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5071                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5072
5073                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5074                 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5075                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5076                 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5077
5078                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish).unwrap();
5079                 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5080                 assert!(node_1_shutdown == node_1_2nd_shutdown);
5081
5082                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish).unwrap();
5083                 let node_0_2nd_shutdown = if recv_count > 0 {
5084                         let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5085                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5086                         node_0_2nd_shutdown
5087                 } else {
5088                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5089                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5090                         get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
5091                 };
5092                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown).unwrap();
5093
5094                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5095                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5096
5097                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
5098                 check_added_monitors!(nodes[2], 1);
5099                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5100                 assert!(updates.update_add_htlcs.is_empty());
5101                 assert!(updates.update_fail_htlcs.is_empty());
5102                 assert!(updates.update_fail_malformed_htlcs.is_empty());
5103                 assert!(updates.update_fee.is_none());
5104                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5105                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
5106                 check_added_monitors!(nodes[1], 1);
5107                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5108                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
5109
5110                 assert!(updates_2.update_add_htlcs.is_empty());
5111                 assert!(updates_2.update_fail_htlcs.is_empty());
5112                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
5113                 assert!(updates_2.update_fee.is_none());
5114                 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
5115                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
5116                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
5117
5118                 let events = nodes[0].node.get_and_clear_pending_events();
5119                 assert_eq!(events.len(), 1);
5120                 match events[0] {
5121                         Event::PaymentSent { ref payment_preimage } => {
5122                                 assert_eq!(our_payment_preimage, *payment_preimage);
5123                         },
5124                         _ => panic!("Unexpected event"),
5125                 }
5126
5127                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5128                 if recv_count > 0 {
5129                         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5130                         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5131                         assert!(node_1_closing_signed.is_some());
5132                 }
5133
5134                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5135                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5136
5137                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5138                 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5139                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5140                 if recv_count == 0 {
5141                         // If all closing_signeds weren't delivered we can just resume where we left off...
5142                         let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5143
5144                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish).unwrap();
5145                         let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5146                         assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
5147
5148                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish).unwrap();
5149                         let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5150                         assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
5151
5152                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown).unwrap();
5153                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5154
5155                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown).unwrap();
5156                         let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5157                         assert!(node_0_closing_signed == node_0_2nd_closing_signed);
5158
5159                         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed).unwrap();
5160                         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5161                         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5162                         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5163                         assert!(node_0_none.is_none());
5164                 } else {
5165                         // If one node, however, received + responded with an identical closing_signed we end
5166                         // up erroring and node[0] will try to broadcast its own latest commitment transaction.
5167                         // There isn't really anything better we can do simply, but in the future we might
5168                         // explore storing a set of recently-closed channels that got disconnected during
5169                         // closing_signed and avoiding broadcasting local commitment txn for some timeout to
5170                         // give our counterparty enough time to (potentially) broadcast a cooperative closing
5171                         // transaction.
5172                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5173
5174                         if let Err(msgs::HandleError{action: Some(msgs::ErrorAction::SendErrorMessage{msg}), ..}) =
5175                                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish) {
5176                                 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
5177                                 let msgs::ErrorMessage {ref channel_id, ..} = msg;
5178                                 assert_eq!(*channel_id, chan_1.2);
5179                         } else { panic!("Needed SendErrorMessage close"); }
5180
5181                         // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
5182                         // checks it, but in this case nodes[0] didn't ever get a chance to receive a
5183                         // closing_signed so we do it ourselves
5184                         let events = nodes[0].node.get_and_clear_pending_msg_events();
5185                         assert_eq!(events.len(), 1);
5186                         match events[0] {
5187                                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5188                                         assert_eq!(msg.contents.flags & 2, 2);
5189                                 },
5190                                 _ => panic!("Unexpected event"),
5191                         }
5192                 }
5193
5194                 assert!(nodes[0].node.list_channels().is_empty());
5195
5196                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5197                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5198                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5199                 assert!(nodes[1].node.list_channels().is_empty());
5200                 assert!(nodes[2].node.list_channels().is_empty());
5201         }
5202
5203         #[test]
5204         fn test_shutdown_rebroadcast() {
5205                 do_test_shutdown_rebroadcast(0);
5206                 do_test_shutdown_rebroadcast(1);
5207                 do_test_shutdown_rebroadcast(2);
5208         }
5209
5210         #[test]
5211         fn fake_network_test() {
5212                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5213                 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
5214                 let nodes = create_network(4);
5215
5216                 // Create some initial channels
5217                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5218                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5219                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5220
5221                 // Rebalance the network a bit by relaying one payment through all the channels...
5222                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5223                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5224                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5225                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5226
5227                 // Send some more payments
5228                 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
5229                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
5230                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
5231
5232                 // Test failure packets
5233                 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
5234                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
5235
5236                 // Add a new channel that skips 3
5237                 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
5238
5239                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
5240                 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
5241                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5242                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5243                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5244                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5245                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5246
5247                 // Do some rebalance loop payments, simultaneously
5248                 let mut hops = Vec::with_capacity(3);
5249                 hops.push(RouteHop {
5250                         pubkey: nodes[2].node.get_our_node_id(),
5251                         short_channel_id: chan_2.0.contents.short_channel_id,
5252                         fee_msat: 0,
5253                         cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
5254                 });
5255                 hops.push(RouteHop {
5256                         pubkey: nodes[3].node.get_our_node_id(),
5257                         short_channel_id: chan_3.0.contents.short_channel_id,
5258                         fee_msat: 0,
5259                         cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
5260                 });
5261                 hops.push(RouteHop {
5262                         pubkey: nodes[1].node.get_our_node_id(),
5263                         short_channel_id: chan_4.0.contents.short_channel_id,
5264                         fee_msat: 1000000,
5265                         cltv_expiry_delta: TEST_FINAL_CLTV,
5266                 });
5267                 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;
5268                 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;
5269                 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
5270
5271                 let mut hops = Vec::with_capacity(3);
5272                 hops.push(RouteHop {
5273                         pubkey: nodes[3].node.get_our_node_id(),
5274                         short_channel_id: chan_4.0.contents.short_channel_id,
5275                         fee_msat: 0,
5276                         cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
5277                 });
5278                 hops.push(RouteHop {
5279                         pubkey: nodes[2].node.get_our_node_id(),
5280                         short_channel_id: chan_3.0.contents.short_channel_id,
5281                         fee_msat: 0,
5282                         cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
5283                 });
5284                 hops.push(RouteHop {
5285                         pubkey: nodes[1].node.get_our_node_id(),
5286                         short_channel_id: chan_2.0.contents.short_channel_id,
5287                         fee_msat: 1000000,
5288                         cltv_expiry_delta: TEST_FINAL_CLTV,
5289                 });
5290                 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;
5291                 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;
5292                 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
5293
5294                 // Claim the rebalances...
5295                 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
5296                 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
5297
5298                 // Add a duplicate new channel from 2 to 4
5299                 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3);
5300
5301                 // Send some payments across both channels
5302                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5303                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5304                 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5305
5306                 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
5307
5308                 //TODO: Test that routes work again here as we've been notified that the channel is full
5309
5310                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
5311                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
5312                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
5313
5314                 // Close down the channels...
5315                 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
5316                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
5317                 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
5318                 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
5319                 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
5320         }
5321
5322         #[test]
5323         fn duplicate_htlc_test() {
5324                 // Test that we accept duplicate payment_hash HTLCs across the network and that
5325                 // claiming/failing them are all separate and don't effect each other
5326                 let mut nodes = create_network(6);
5327
5328                 // Create some initial channels to route via 3 to 4/5 from 0/1/2
5329                 create_announced_chan_between_nodes(&nodes, 0, 3);
5330                 create_announced_chan_between_nodes(&nodes, 1, 3);
5331                 create_announced_chan_between_nodes(&nodes, 2, 3);
5332                 create_announced_chan_between_nodes(&nodes, 3, 4);
5333                 create_announced_chan_between_nodes(&nodes, 3, 5);
5334
5335                 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
5336
5337                 *nodes[0].network_payment_count.borrow_mut() -= 1;
5338                 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
5339
5340                 *nodes[0].network_payment_count.borrow_mut() -= 1;
5341                 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
5342
5343                 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
5344                 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
5345                 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
5346         }
5347
5348         #[derive(PartialEq)]
5349         enum HTLCType { NONE, TIMEOUT, SUCCESS }
5350         /// Tests that the given node has broadcast transactions for the given Channel
5351         ///
5352         /// First checks that the latest local commitment tx has been broadcast, unless an explicit
5353         /// commitment_tx is provided, which may be used to test that a remote commitment tx was
5354         /// broadcast and the revoked outputs were claimed.
5355         ///
5356         /// Next tests that there is (or is not) a transaction that spends the commitment transaction
5357         /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
5358         ///
5359         /// All broadcast transactions must be accounted for in one of the above three types of we'll
5360         /// also fail.
5361         fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
5362                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5363                 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
5364
5365                 let mut res = Vec::with_capacity(2);
5366                 node_txn.retain(|tx| {
5367                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
5368                                 check_spends!(tx, chan.3.clone());
5369                                 if commitment_tx.is_none() {
5370                                         res.push(tx.clone());
5371                                 }
5372                                 false
5373                         } else { true }
5374                 });
5375                 if let Some(explicit_tx) = commitment_tx {
5376                         res.push(explicit_tx.clone());
5377                 }
5378
5379                 assert_eq!(res.len(), 1);
5380
5381                 if has_htlc_tx != HTLCType::NONE {
5382                         node_txn.retain(|tx| {
5383                                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
5384                                         check_spends!(tx, res[0].clone());
5385                                         if has_htlc_tx == HTLCType::TIMEOUT {
5386                                                 assert!(tx.lock_time != 0);
5387                                         } else {
5388                                                 assert!(tx.lock_time == 0);
5389                                         }
5390                                         res.push(tx.clone());
5391                                         false
5392                                 } else { true }
5393                         });
5394                         assert!(res.len() == 2 || res.len() == 3);
5395                         if res.len() == 3 {
5396                                 assert_eq!(res[1], res[2]);
5397                         }
5398                 }
5399
5400                 assert!(node_txn.is_empty());
5401                 res
5402         }
5403
5404         /// Tests that the given node has broadcast a claim transaction against the provided revoked
5405         /// HTLC transaction.
5406         fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
5407                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5408                 assert_eq!(node_txn.len(), 1);
5409                 node_txn.retain(|tx| {
5410                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
5411                                 check_spends!(tx, revoked_tx.clone());
5412                                 false
5413                         } else { true }
5414                 });
5415                 assert!(node_txn.is_empty());
5416         }
5417
5418         fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
5419                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5420
5421                 assert!(node_txn.len() >= 1);
5422                 assert_eq!(node_txn[0].input.len(), 1);
5423                 let mut found_prev = false;
5424
5425                 for tx in prev_txn {
5426                         if node_txn[0].input[0].previous_output.txid == tx.txid() {
5427                                 check_spends!(node_txn[0], tx.clone());
5428                                 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
5429                                 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
5430
5431                                 found_prev = true;
5432                                 break;
5433                         }
5434                 }
5435                 assert!(found_prev);
5436
5437                 let mut res = Vec::new();
5438                 mem::swap(&mut *node_txn, &mut res);
5439                 res
5440         }
5441
5442         fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
5443                 let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
5444                 assert_eq!(events_1.len(), 1);
5445                 let as_update = match events_1[0] {
5446                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5447                                 msg.clone()
5448                         },
5449                         _ => panic!("Unexpected event"),
5450                 };
5451
5452                 let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
5453                 assert_eq!(events_2.len(), 1);
5454                 let bs_update = match events_2[0] {
5455                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5456                                 msg.clone()
5457                         },
5458                         _ => panic!("Unexpected event"),
5459                 };
5460
5461                 for node in nodes {
5462                         node.router.handle_channel_update(&as_update).unwrap();
5463                         node.router.handle_channel_update(&bs_update).unwrap();
5464                 }
5465         }
5466
5467         macro_rules! expect_pending_htlcs_forwardable {
5468                 ($node: expr) => {{
5469                         let events = $node.node.get_and_clear_pending_events();
5470                         assert_eq!(events.len(), 1);
5471                         match events[0] {
5472                                 Event::PendingHTLCsForwardable { .. } => { },
5473                                 _ => panic!("Unexpected event"),
5474                         };
5475                         $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
5476                         $node.node.process_pending_htlc_forwards();
5477                 }}
5478         }
5479
5480         fn do_channel_reserve_test(test_recv: bool) {
5481                 use util::rng;
5482                 use std::sync::atomic::Ordering;
5483                 use ln::msgs::HandleError;
5484
5485                 macro_rules! get_channel_value_stat {
5486                         ($node: expr, $channel_id: expr) => {{
5487                                 let chan_lock = $node.node.channel_state.lock().unwrap();
5488                                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
5489                                 chan.get_value_stat()
5490                         }}
5491                 }
5492
5493                 let mut nodes = create_network(3);
5494                 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001);
5495                 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001);
5496
5497                 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
5498                 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
5499
5500                 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
5501                 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
5502
5503                 macro_rules! get_route_and_payment_hash {
5504                         ($recv_value: expr) => {{
5505                                 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
5506                                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5507                                 (route, payment_hash, payment_preimage)
5508                         }}
5509                 };
5510
5511                 macro_rules! expect_forward {
5512                         ($node: expr) => {{
5513                                 let mut events = $node.node.get_and_clear_pending_msg_events();
5514                                 assert_eq!(events.len(), 1);
5515                                 check_added_monitors!($node, 1);
5516                                 let payment_event = SendEvent::from_event(events.remove(0));
5517                                 payment_event
5518                         }}
5519                 }
5520
5521                 macro_rules! expect_payment_received {
5522                         ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
5523                                 let events = $node.node.get_and_clear_pending_events();
5524                                 assert_eq!(events.len(), 1);
5525                                 match events[0] {
5526                                         Event::PaymentReceived { ref payment_hash, amt } => {
5527                                                 assert_eq!($expected_payment_hash, *payment_hash);
5528                                                 assert_eq!($expected_recv_value, amt);
5529                                         },
5530                                         _ => panic!("Unexpected event"),
5531                                 }
5532                         }
5533                 };
5534
5535                 let feemsat = 239; // somehow we know?
5536                 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
5537
5538                 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
5539
5540                 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
5541                 {
5542                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
5543                         assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
5544                         let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
5545                         match err {
5546                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
5547                                 _ => panic!("Unknown error variants"),
5548                         }
5549                 }
5550
5551                 let mut htlc_id = 0;
5552                 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
5553                 // nodes[0]'s wealth
5554                 loop {
5555                         let amt_msat = recv_value_0 + total_fee_msat;
5556                         if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
5557                                 break;
5558                         }
5559                         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
5560                         htlc_id += 1;
5561
5562                         let (stat01_, stat11_, stat12_, stat22_) = (
5563                                 get_channel_value_stat!(nodes[0], chan_1.2),
5564                                 get_channel_value_stat!(nodes[1], chan_1.2),
5565                                 get_channel_value_stat!(nodes[1], chan_2.2),
5566                                 get_channel_value_stat!(nodes[2], chan_2.2),
5567                         );
5568
5569                         assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
5570                         assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
5571                         assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
5572                         assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
5573                         stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
5574                 }
5575
5576                 {
5577                         let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
5578                         // attempt to get channel_reserve violation
5579                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
5580                         let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
5581                         match err {
5582                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5583                                 _ => panic!("Unknown error variants"),
5584                         }
5585                 }
5586
5587                 // adding pending output
5588                 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
5589                 let amt_msat_1 = recv_value_1 + total_fee_msat;
5590
5591                 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
5592                 let payment_event_1 = {
5593                         nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
5594                         check_added_monitors!(nodes[0], 1);
5595
5596                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5597                         assert_eq!(events.len(), 1);
5598                         SendEvent::from_event(events.remove(0))
5599                 };
5600                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]).unwrap();
5601
5602                 // channel reserve test with htlc pending output > 0
5603                 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
5604                 {
5605                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5606                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5607                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5608                                 _ => panic!("Unknown error variants"),
5609                         }
5610                 }
5611
5612                 {
5613                         // test channel_reserve test on nodes[1] side
5614                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5615
5616                         // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
5617                         let secp_ctx = Secp256k1::new();
5618                         let session_priv = SecretKey::from_slice(&secp_ctx, &{
5619                                 let mut session_key = [0; 32];
5620                                 rng::fill_bytes(&mut session_key);
5621                                 session_key
5622                         }).expect("RNG is bad!");
5623
5624                         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5625                         let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
5626                         let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height).unwrap();
5627                         let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
5628                         let msg = msgs::UpdateAddHTLC {
5629                                 channel_id: chan_1.2,
5630                                 htlc_id,
5631                                 amount_msat: htlc_msat,
5632                                 payment_hash: our_payment_hash,
5633                                 cltv_expiry: htlc_cltv,
5634                                 onion_routing_packet: onion_packet,
5635                         };
5636
5637                         if test_recv {
5638                                 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).err().unwrap();
5639                                 match err {
5640                                         HandleError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
5641                                 }
5642                                 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
5643                                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5644                                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5645                                 let channel_close_broadcast = nodes[1].node.get_and_clear_pending_msg_events();
5646                                 assert_eq!(channel_close_broadcast.len(), 1);
5647                                 match channel_close_broadcast[0] {
5648                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5649                                                 assert_eq!(msg.contents.flags & 2, 2);
5650                                         },
5651                                         _ => panic!("Unexpected event"),
5652                                 }
5653                                 return;
5654                         }
5655                 }
5656
5657                 // split the rest to test holding cell
5658                 let recv_value_21 = recv_value_2/2;
5659                 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
5660                 {
5661                         let stat = get_channel_value_stat!(nodes[0], chan_1.2);
5662                         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);
5663                 }
5664
5665                 // now see if they go through on both sides
5666                 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
5667                 // but this will stuck in the holding cell
5668                 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
5669                 check_added_monitors!(nodes[0], 0);
5670                 let events = nodes[0].node.get_and_clear_pending_events();
5671                 assert_eq!(events.len(), 0);
5672
5673                 // test with outbound holding cell amount > 0
5674                 {
5675                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
5676                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5677                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5678                                 _ => panic!("Unknown error variants"),
5679                         }
5680                 }
5681
5682                 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
5683                 // this will also stuck in the holding cell
5684                 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
5685                 check_added_monitors!(nodes[0], 0);
5686                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
5687                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5688
5689                 // flush the pending htlc
5690                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg).unwrap();
5691                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5692                 check_added_monitors!(nodes[1], 1);
5693
5694                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
5695                 check_added_monitors!(nodes[0], 1);
5696                 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5697
5698                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed).unwrap();
5699                 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
5700                 // No commitment_signed so get_event_msg's assert(len == 1) passes
5701                 check_added_monitors!(nodes[0], 1);
5702
5703                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
5704                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5705                 check_added_monitors!(nodes[1], 1);
5706
5707                 expect_pending_htlcs_forwardable!(nodes[1]);
5708
5709                 let ref payment_event_11 = expect_forward!(nodes[1]);
5710                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]).unwrap();
5711                 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
5712
5713                 expect_pending_htlcs_forwardable!(nodes[2]);
5714                 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
5715
5716                 // flush the htlcs in the holding cell
5717                 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
5718                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]).unwrap();
5719                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]).unwrap();
5720                 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
5721                 expect_pending_htlcs_forwardable!(nodes[1]);
5722
5723                 let ref payment_event_3 = expect_forward!(nodes[1]);
5724                 assert_eq!(payment_event_3.msgs.len(), 2);
5725                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]).unwrap();
5726                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]).unwrap();
5727
5728                 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
5729                 expect_pending_htlcs_forwardable!(nodes[2]);
5730
5731                 let events = nodes[2].node.get_and_clear_pending_events();
5732                 assert_eq!(events.len(), 2);
5733                 match events[0] {
5734                         Event::PaymentReceived { ref payment_hash, amt } => {
5735                                 assert_eq!(our_payment_hash_21, *payment_hash);
5736                                 assert_eq!(recv_value_21, amt);
5737                         },
5738                         _ => panic!("Unexpected event"),
5739                 }
5740                 match events[1] {
5741                         Event::PaymentReceived { ref payment_hash, amt } => {
5742                                 assert_eq!(our_payment_hash_22, *payment_hash);
5743                                 assert_eq!(recv_value_22, amt);
5744                         },
5745                         _ => panic!("Unexpected event"),
5746                 }
5747
5748                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
5749                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
5750                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
5751
5752                 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);
5753                 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
5754                 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
5755                 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
5756
5757                 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
5758                 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
5759         }
5760
5761         #[test]
5762         fn channel_reserve_test() {
5763                 do_channel_reserve_test(false);
5764                 do_channel_reserve_test(true);
5765         }
5766
5767         #[test]
5768         fn channel_monitor_network_test() {
5769                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5770                 // tests that ChannelMonitor is able to recover from various states.
5771                 let nodes = create_network(5);
5772
5773                 // Create some initial channels
5774                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5775                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5776                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5777                 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5778
5779                 // Rebalance the network a bit by relaying one payment through all the channels...
5780                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5781                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5782                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5783                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5784
5785                 // Simple case with no pending HTLCs:
5786                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
5787                 {
5788                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
5789                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5790                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5791                         test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
5792                 }
5793                 get_announce_close_broadcast_events(&nodes, 0, 1);
5794                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5795                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5796
5797                 // One pending HTLC is discarded by the force-close:
5798                 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
5799
5800                 // Simple case of one pending HTLC to HTLC-Timeout
5801                 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
5802                 {
5803                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
5804                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5805                         nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5806                         test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
5807                 }
5808                 get_announce_close_broadcast_events(&nodes, 1, 2);
5809                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5810                 assert_eq!(nodes[2].node.list_channels().len(), 1);
5811
5812                 macro_rules! claim_funds {
5813                         ($node: expr, $prev_node: expr, $preimage: expr) => {
5814                                 {
5815                                         assert!($node.node.claim_funds($preimage));
5816                                         check_added_monitors!($node, 1);
5817
5818                                         let events = $node.node.get_and_clear_pending_msg_events();
5819                                         assert_eq!(events.len(), 1);
5820                                         match events[0] {
5821                                                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
5822                                                         assert!(update_add_htlcs.is_empty());
5823                                                         assert!(update_fail_htlcs.is_empty());
5824                                                         assert_eq!(*node_id, $prev_node.node.get_our_node_id());
5825                                                 },
5826                                                 _ => panic!("Unexpected event"),
5827                                         };
5828                                 }
5829                         }
5830                 }
5831
5832                 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
5833                 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
5834                 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
5835                 {
5836                         let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
5837
5838                         // Claim the payment on nodes[3], giving it knowledge of the preimage
5839                         claim_funds!(nodes[3], nodes[2], payment_preimage_1);
5840
5841                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5842                         nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
5843
5844                         check_preimage_claim(&nodes[3], &node_txn);
5845                 }
5846                 get_announce_close_broadcast_events(&nodes, 2, 3);
5847                 assert_eq!(nodes[2].node.list_channels().len(), 0);
5848                 assert_eq!(nodes[3].node.list_channels().len(), 1);
5849
5850                 { // Cheat and reset nodes[4]'s height to 1
5851                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5852                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![] }, 1);
5853                 }
5854
5855                 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
5856                 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
5857                 // One pending HTLC to time out:
5858                 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
5859                 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
5860                 // buffer space).
5861
5862                 {
5863                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5864                         nodes[3].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5865                         for i in 3..TEST_FINAL_CLTV + 2 + HTLC_FAIL_TIMEOUT_BLOCKS + 1 {
5866                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5867                                 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5868                         }
5869
5870                         let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
5871
5872                         // Claim the payment on nodes[4], giving it knowledge of the preimage
5873                         claim_funds!(nodes[4], nodes[3], payment_preimage_2);
5874
5875                         header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5876                         nodes[4].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5877                         for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
5878                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5879                                 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5880                         }
5881
5882                         test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
5883
5884                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5885                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
5886
5887                         check_preimage_claim(&nodes[4], &node_txn);
5888                 }
5889                 get_announce_close_broadcast_events(&nodes, 3, 4);
5890                 assert_eq!(nodes[3].node.list_channels().len(), 0);
5891                 assert_eq!(nodes[4].node.list_channels().len(), 0);
5892         }
5893
5894         #[test]
5895         fn test_justice_tx() {
5896                 // Test justice txn built on revoked HTLC-Success tx, against both sides
5897
5898                 let nodes = create_network(2);
5899                 // Create some new channels:
5900                 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
5901
5902                 // A pending HTLC which will be revoked:
5903                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5904                 // Get the will-be-revoked local txn from nodes[0]
5905                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5906                 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
5907                 assert_eq!(revoked_local_txn[0].input.len(), 1);
5908                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
5909                 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
5910                 assert_eq!(revoked_local_txn[1].input.len(), 1);
5911                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
5912                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
5913                 // Revoke the old state
5914                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
5915
5916                 {
5917                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5918                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5919                         {
5920                                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5921                                 assert_eq!(node_txn.len(), 3);
5922                                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5923                                 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
5924
5925                                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5926                                 node_txn.swap_remove(0);
5927                         }
5928                         test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
5929
5930                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5931                         let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
5932                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5933                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5934                         test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
5935                 }
5936                 get_announce_close_broadcast_events(&nodes, 0, 1);
5937
5938                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5939                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5940
5941                 // We test justice_tx build by A on B's revoked HTLC-Success tx
5942                 // Create some new channels:
5943                 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
5944
5945                 // A pending HTLC which will be revoked:
5946                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5947                 // Get the will-be-revoked local txn from B
5948                 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5949                 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
5950                 assert_eq!(revoked_local_txn[0].input.len(), 1);
5951                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
5952                 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
5953                 // Revoke the old state
5954                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
5955                 {
5956                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5957                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5958                         {
5959                                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5960                                 assert_eq!(node_txn.len(), 3);
5961                                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5962                                 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
5963
5964                                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5965                                 node_txn.swap_remove(0);
5966                         }
5967                         test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
5968
5969                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5970                         let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
5971                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5972                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5973                         test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone());
5974                 }
5975                 get_announce_close_broadcast_events(&nodes, 0, 1);
5976                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5977                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5978         }
5979
5980         #[test]
5981         fn revoked_output_claim() {
5982                 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
5983                 // transaction is broadcast by its counterparty
5984                 let nodes = create_network(2);
5985                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5986                 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
5987                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5988                 assert_eq!(revoked_local_txn.len(), 1);
5989                 // Only output is the full channel value back to nodes[0]:
5990                 assert_eq!(revoked_local_txn[0].output.len(), 1);
5991                 // Send a payment through, updating everyone's latest commitment txn
5992                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
5993
5994                 // Inform nodes[1] that nodes[0] broadcast a stale tx
5995                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5996                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5997                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5998                 assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
5999
6000                 assert_eq!(node_txn[0], node_txn[2]);
6001
6002                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
6003                 check_spends!(node_txn[1], chan_1.3.clone());
6004
6005                 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
6006                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6007                 get_announce_close_broadcast_events(&nodes, 0, 1);
6008         }
6009
6010         #[test]
6011         fn claim_htlc_outputs_shared_tx() {
6012                 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
6013                 let nodes = create_network(2);
6014
6015                 // Create some new channel:
6016                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6017
6018                 // Rebalance the network to generate htlc in the two directions
6019                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6020                 // 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
6021                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6022                 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6023
6024                 // Get the will-be-revoked local txn from node[0]
6025                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6026                 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
6027                 assert_eq!(revoked_local_txn[0].input.len(), 1);
6028                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
6029                 assert_eq!(revoked_local_txn[1].input.len(), 1);
6030                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
6031                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
6032                 check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
6033
6034                 //Revoke the old state
6035                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6036
6037                 {
6038                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6039                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6040                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6041
6042                         let events = nodes[1].node.get_and_clear_pending_events();
6043                         assert_eq!(events.len(), 1);
6044                         match events[0] {
6045                                 Event::PaymentFailed { payment_hash, .. } => {
6046                                         assert_eq!(payment_hash, payment_hash_2);
6047                                 },
6048                                 _ => panic!("Unexpected event"),
6049                         }
6050
6051                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6052                         assert_eq!(node_txn.len(), 4);
6053
6054                         assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
6055                         check_spends!(node_txn[0], revoked_local_txn[0].clone());
6056
6057                         assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
6058
6059                         let mut witness_lens = BTreeSet::new();
6060                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6061                         witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
6062                         witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
6063                         assert_eq!(witness_lens.len(), 3);
6064                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6065                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
6066                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
6067
6068                         // Next nodes[1] broadcasts its current local tx state:
6069                         assert_eq!(node_txn[1].input.len(), 1);
6070                         assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
6071
6072                         assert_eq!(node_txn[2].input.len(), 1);
6073                         let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
6074                         assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
6075                         assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
6076                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6077                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
6078                 }
6079                 get_announce_close_broadcast_events(&nodes, 0, 1);
6080                 assert_eq!(nodes[0].node.list_channels().len(), 0);
6081                 assert_eq!(nodes[1].node.list_channels().len(), 0);
6082         }
6083
6084         #[test]
6085         fn claim_htlc_outputs_single_tx() {
6086                 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
6087                 let nodes = create_network(2);
6088
6089                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6090
6091                 // Rebalance the network to generate htlc in the two directions
6092                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6093                 // 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
6094                 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
6095                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6096                 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6097
6098                 // Get the will-be-revoked local txn from node[0]
6099                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6100
6101                 //Revoke the old state
6102                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6103
6104                 {
6105                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6106                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6107                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6108
6109                         let events = nodes[1].node.get_and_clear_pending_events();
6110                         assert_eq!(events.len(), 1);
6111                         match events[0] {
6112                                 Event::PaymentFailed { payment_hash, .. } => {
6113                                         assert_eq!(payment_hash, payment_hash_2);
6114                                 },
6115                                 _ => panic!("Unexpected event"),
6116                         }
6117
6118                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6119                         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)
6120
6121                         assert_eq!(node_txn[0], node_txn[7]);
6122                         assert_eq!(node_txn[1], node_txn[8]);
6123                         assert_eq!(node_txn[2], node_txn[9]);
6124                         assert_eq!(node_txn[3], node_txn[10]);
6125                         assert_eq!(node_txn[4], node_txn[11]);
6126                         assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcated by ChannelManger
6127                         assert_eq!(node_txn[4], node_txn[6]);
6128
6129                         assert_eq!(node_txn[0].input.len(), 1);
6130                         assert_eq!(node_txn[1].input.len(), 1);
6131                         assert_eq!(node_txn[2].input.len(), 1);
6132
6133                         let mut revoked_tx_map = HashMap::new();
6134                         revoked_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
6135                         node_txn[0].verify(&revoked_tx_map).unwrap();
6136                         node_txn[1].verify(&revoked_tx_map).unwrap();
6137                         node_txn[2].verify(&revoked_tx_map).unwrap();
6138
6139                         let mut witness_lens = BTreeSet::new();
6140                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6141                         witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
6142                         witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
6143                         assert_eq!(witness_lens.len(), 3);
6144                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6145                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
6146                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
6147
6148                         assert_eq!(node_txn[3].input.len(), 1);
6149                         check_spends!(node_txn[3], chan_1.3.clone());
6150
6151                         assert_eq!(node_txn[4].input.len(), 1);
6152                         let witness_script = node_txn[4].input[0].witness.last().unwrap();
6153                         assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
6154                         assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
6155                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6156                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
6157                 }
6158                 get_announce_close_broadcast_events(&nodes, 0, 1);
6159                 assert_eq!(nodes[0].node.list_channels().len(), 0);
6160                 assert_eq!(nodes[1].node.list_channels().len(), 0);
6161         }
6162
6163         #[test]
6164         fn test_htlc_on_chain_success() {
6165                 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
6166                 // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
6167                 // broadcasting the right event to other nodes in payment path.
6168                 // A --------------------> B ----------------------> C (preimage)
6169                 // First, C should claim the HTLC output via HTLC-Success when its own latest local
6170                 // commitment transaction was broadcast.
6171                 // Then, B should learn the preimage from said transactions, attempting to claim backwards
6172                 // towards B.
6173                 // B should be able to claim via preimage if A then broadcasts its local tx.
6174                 // Finally, when A sees B's latest local commitment transaction it should be able to claim
6175                 // the HTLC output via the preimage it learned (which, once confirmed should generate a
6176                 // PaymentSent event).
6177
6178                 let nodes = create_network(3);
6179
6180                 // Create some initial channels
6181                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6182                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6183
6184                 // Rebalance the network a bit by relaying one payment through all the channels...
6185                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6186                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6187
6188                 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
6189                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6190
6191                 // Broadcast legit commitment tx from C on B's chain
6192                 // Broadcast HTLC Success transation by C on received output from C's commitment tx on B's chain
6193                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6194                 assert_eq!(commitment_tx.len(), 1);
6195                 check_spends!(commitment_tx[0], chan_2.3.clone());
6196                 nodes[2].node.claim_funds(our_payment_preimage);
6197                 check_added_monitors!(nodes[2], 1);
6198                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6199                 assert!(updates.update_add_htlcs.is_empty());
6200                 assert!(updates.update_fail_htlcs.is_empty());
6201                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6202                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
6203
6204                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6205                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6206                 assert_eq!(events.len(), 1);
6207                 match events[0] {
6208                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6209                         _ => panic!("Unexpected event"),
6210                 }
6211                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
6212                 assert_eq!(node_txn.len(), 3);
6213                 assert_eq!(node_txn[1], commitment_tx[0]);
6214                 assert_eq!(node_txn[0], node_txn[2]);
6215                 check_spends!(node_txn[0], commitment_tx[0].clone());
6216                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6217                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6218                 assert_eq!(node_txn[0].lock_time, 0);
6219
6220                 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
6221                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: node_txn}, 1);
6222                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6223                 {
6224                         let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
6225                         assert_eq!(added_monitors.len(), 1);
6226                         assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
6227                         added_monitors.clear();
6228                 }
6229                 assert_eq!(events.len(), 2);
6230                 match events[0] {
6231                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6232                         _ => panic!("Unexpected event"),
6233                 }
6234                 match events[1] {
6235                         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, .. } } => {
6236                                 assert!(update_add_htlcs.is_empty());
6237                                 assert!(update_fail_htlcs.is_empty());
6238                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6239                                 assert!(update_fail_malformed_htlcs.is_empty());
6240                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6241                         },
6242                         _ => panic!("Unexpected event"),
6243                 };
6244                 {
6245                         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
6246                         // commitment transaction with a corresponding HTLC-Timeout transaction, as well as a
6247                         // timeout-claim of the output that nodes[2] just claimed via success.
6248                         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)
6249                         assert_eq!(node_txn.len(), 4);
6250                         assert_eq!(node_txn[0], node_txn[3]);
6251                         check_spends!(node_txn[0], commitment_tx[0].clone());
6252                         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6253                         assert_ne!(node_txn[0].lock_time, 0);
6254                         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
6255                         check_spends!(node_txn[1], chan_2.3.clone());
6256                         check_spends!(node_txn[2], node_txn[1].clone());
6257                         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6258                         assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6259                         assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6260                         assert_ne!(node_txn[2].lock_time, 0);
6261                         node_txn.clear();
6262                 }
6263
6264                 // Broadcast legit commitment tx from A on B's chain
6265                 // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
6266                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6267                 check_spends!(commitment_tx[0], chan_1.3.clone());
6268                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6269                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6270                 assert_eq!(events.len(), 1);
6271                 match events[0] {
6272                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6273                         _ => panic!("Unexpected event"),
6274                 }
6275                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 1 (HTLC-Success) * 2 (block-rescan)
6276                 assert_eq!(node_txn.len(), 3);
6277                 assert_eq!(node_txn[0], node_txn[2]);
6278                 check_spends!(node_txn[0], commitment_tx[0].clone());
6279                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6280                 assert_eq!(node_txn[0].lock_time, 0);
6281                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
6282                 check_spends!(node_txn[1], chan_1.3.clone());
6283                 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6284                 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
6285                 // we already checked the same situation with A.
6286
6287                 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
6288                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
6289                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6290                 assert_eq!(events.len(), 1);
6291                 match events[0] {
6292                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6293                         _ => panic!("Unexpected event"),
6294                 }
6295                 let events = nodes[0].node.get_and_clear_pending_events();
6296                 assert_eq!(events.len(), 1);
6297                 match events[0] {
6298                         Event::PaymentSent { payment_preimage } => {
6299                                 assert_eq!(payment_preimage, our_payment_preimage);
6300                         },
6301                         _ => panic!("Unexpected event"),
6302                 }
6303                 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)
6304                 assert_eq!(node_txn.len(), 4);
6305                 assert_eq!(node_txn[0], node_txn[3]);
6306                 check_spends!(node_txn[0], commitment_tx[0].clone());
6307                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6308                 assert_ne!(node_txn[0].lock_time, 0);
6309                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6310                 check_spends!(node_txn[1], chan_1.3.clone());
6311                 check_spends!(node_txn[2], node_txn[1].clone());
6312                 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6313                 assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6314                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6315                 assert_ne!(node_txn[2].lock_time, 0);
6316         }
6317
6318         #[test]
6319         fn test_htlc_on_chain_timeout() {
6320                 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
6321                 // ChainWatchInterface and timeout the HTLC  bacward accordingly. So here we test that ChannelManager is
6322                 // broadcasting the right event to other nodes in payment path.
6323                 // A ------------------> B ----------------------> C (timeout)
6324                 //    B's commitment tx                 C's commitment tx
6325                 //            \                                  \
6326                 //         B's HTLC timeout tx               B's timeout tx
6327
6328                 let nodes = create_network(3);
6329
6330                 // Create some intial channels
6331                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6332                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6333
6334                 // Rebalance the network a bit by relaying one payment thorugh all the channels...
6335                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6336                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6337
6338                 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
6339                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6340
6341                 // Brodacast legit commitment tx from C on B's chain
6342                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6343                 check_spends!(commitment_tx[0], chan_2.3.clone());
6344                 nodes[2].node.fail_htlc_backwards(&payment_hash, PaymentFailReason::PreimageUnknown);
6345                 {
6346                         let mut added_monitors = nodes[2].chan_monitor.added_monitors.lock().unwrap();
6347                         assert_eq!(added_monitors.len(), 1);
6348                         added_monitors.clear();
6349                 }
6350                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6351                 assert_eq!(events.len(), 1);
6352                 match events[0] {
6353                         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, .. } } => {
6354                                 assert!(update_add_htlcs.is_empty());
6355                                 assert!(!update_fail_htlcs.is_empty());
6356                                 assert!(update_fulfill_htlcs.is_empty());
6357                                 assert!(update_fail_malformed_htlcs.is_empty());
6358                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
6359                         },
6360                         _ => panic!("Unexpected event"),
6361                 };
6362                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6363                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6364                 assert_eq!(events.len(), 1);
6365                 match events[0] {
6366                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6367                         _ => panic!("Unexpected event"),
6368                 }
6369                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
6370                 assert_eq!(node_txn.len(), 1);
6371                 check_spends!(node_txn[0], chan_2.3.clone());
6372                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
6373
6374                 // Broadcast timeout transaction by B on received output fron C's commitment tx on B's chain
6375                 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
6376                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6377                 let timeout_tx;
6378                 {
6379                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6380                         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)
6381                         assert_eq!(node_txn[0], node_txn[5]);
6382                         assert_eq!(node_txn[1], node_txn[6]);
6383                         assert_eq!(node_txn[2], node_txn[7]);
6384                         check_spends!(node_txn[0], commitment_tx[0].clone());
6385                         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6386                         check_spends!(node_txn[1], chan_2.3.clone());
6387                         check_spends!(node_txn[2], node_txn[1].clone());
6388                         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6389                         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6390                         check_spends!(node_txn[3], chan_2.3.clone());
6391                         check_spends!(node_txn[4], node_txn[3].clone());
6392                         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
6393                         assert_eq!(node_txn[4].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6394                         timeout_tx = node_txn[0].clone();
6395                         node_txn.clear();
6396                 }
6397
6398                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![timeout_tx]}, 1);
6399                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6400                 check_added_monitors!(nodes[1], 1);
6401                 assert_eq!(events.len(), 2);
6402                 match events[0] {
6403                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6404                         _ => panic!("Unexpected event"),
6405                 }
6406                 match events[1] {
6407                         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, .. } } => {
6408                                 assert!(update_add_htlcs.is_empty());
6409                                 assert!(!update_fail_htlcs.is_empty());
6410                                 assert!(update_fulfill_htlcs.is_empty());
6411                                 assert!(update_fail_malformed_htlcs.is_empty());
6412                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6413                         },
6414                         _ => panic!("Unexpected event"),
6415                 };
6416                 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
6417                 assert_eq!(node_txn.len(), 0);
6418
6419                 // Broadcast legit commitment tx from B on A's chain
6420                 let commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6421                 check_spends!(commitment_tx[0], chan_1.3.clone());
6422
6423                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6424                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6425                 assert_eq!(events.len(), 1);
6426                 match events[0] {
6427                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6428                         _ => panic!("Unexpected event"),
6429                 }
6430                 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
6431                 assert_eq!(node_txn.len(), 4);
6432                 assert_eq!(node_txn[0], node_txn[3]);
6433                 check_spends!(node_txn[0], commitment_tx[0].clone());
6434                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6435                 check_spends!(node_txn[1], chan_1.3.clone());
6436                 check_spends!(node_txn[2], node_txn[1].clone());
6437                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6438                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6439         }
6440
6441         #[test]
6442         fn test_simple_commitment_revoked_fail_backward() {
6443                 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
6444                 // and fail backward accordingly.
6445
6446                 let nodes = create_network(3);
6447
6448                 // Create some initial channels
6449                 create_announced_chan_between_nodes(&nodes, 0, 1);
6450                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6451
6452                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6453                 // Get the will-be-revoked local txn from nodes[2]
6454                 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6455                 // Revoke the old state
6456                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6457
6458                 route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6459
6460                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6461                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6462                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6463                 check_added_monitors!(nodes[1], 1);
6464                 assert_eq!(events.len(), 2);
6465                 match events[0] {
6466                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6467                         _ => panic!("Unexpected event"),
6468                 }
6469                 match events[1] {
6470                         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, .. } } => {
6471                                 assert!(update_add_htlcs.is_empty());
6472                                 assert_eq!(update_fail_htlcs.len(), 1);
6473                                 assert!(update_fulfill_htlcs.is_empty());
6474                                 assert!(update_fail_malformed_htlcs.is_empty());
6475                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6476
6477                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6478                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6479
6480                                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6481                                 assert_eq!(events.len(), 1);
6482                                 match events[0] {
6483                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6484                                         _ => panic!("Unexpected event"),
6485                                 }
6486                                 let events = nodes[0].node.get_and_clear_pending_events();
6487                                 assert_eq!(events.len(), 1);
6488                                 match events[0] {
6489                                         Event::PaymentFailed { .. } => {},
6490                                         _ => panic!("Unexpected event"),
6491                                 }
6492                         },
6493                         _ => panic!("Unexpected event"),
6494                 }
6495         }
6496
6497         fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool) {
6498                 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
6499                 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
6500                 // commitment transaction anymore.
6501                 // To do this, we have the peer which will broadcast a revoked commitment transaction send
6502                 // a number of update_fail/commitment_signed updates without ever sending the RAA in
6503                 // response to our commitment_signed. This is somewhat misbehavior-y, though not
6504                 // technically disallowed and we should probably handle it reasonably.
6505                 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
6506                 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
6507                 // transactions:
6508                 // * Once we move it out of our holding cell/add it, we will immediately include it in a
6509                 //   commitment_signed (implying it will be in the latest remote commitment transaction).
6510                 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
6511                 //   and once they revoke the previous commitment transaction (allowing us to send a new
6512                 //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
6513                 let mut nodes = create_network(3);
6514
6515                 // Create some initial channels
6516                 create_announced_chan_between_nodes(&nodes, 0, 1);
6517                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6518
6519                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6520                 // Get the will-be-revoked local txn from nodes[2]
6521                 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6522                 // Revoke the old state
6523                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6524
6525                 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6526                 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6527                 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6528
6529                 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, PaymentFailReason::PreimageUnknown));
6530                 check_added_monitors!(nodes[2], 1);
6531                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6532                 assert!(updates.update_add_htlcs.is_empty());
6533                 assert!(updates.update_fulfill_htlcs.is_empty());
6534                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6535                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6536                 assert!(updates.update_fee.is_none());
6537                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6538                 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
6539                 // Drop the last RAA from 3 -> 2
6540
6541                 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, PaymentFailReason::PreimageUnknown));
6542                 check_added_monitors!(nodes[2], 1);
6543                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6544                 assert!(updates.update_add_htlcs.is_empty());
6545                 assert!(updates.update_fulfill_htlcs.is_empty());
6546                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6547                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6548                 assert!(updates.update_fee.is_none());
6549                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6550                 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6551                 check_added_monitors!(nodes[1], 1);
6552                 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
6553                 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6554                 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6555                 check_added_monitors!(nodes[2], 1);
6556
6557                 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, PaymentFailReason::PreimageUnknown));
6558                 check_added_monitors!(nodes[2], 1);
6559                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6560                 assert!(updates.update_add_htlcs.is_empty());
6561                 assert!(updates.update_fulfill_htlcs.is_empty());
6562                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6563                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6564                 assert!(updates.update_fee.is_none());
6565                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6566                 // At this point first_payment_hash has dropped out of the latest two commitment
6567                 // transactions that nodes[1] is tracking...
6568                 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6569                 check_added_monitors!(nodes[1], 1);
6570                 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
6571                 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6572                 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6573                 check_added_monitors!(nodes[2], 1);
6574
6575                 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
6576                 // on nodes[2]'s RAA.
6577                 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
6578                 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6579                 nodes[1].node.send_payment(route, fourth_payment_hash).unwrap();
6580                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
6581                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6582                 check_added_monitors!(nodes[1], 0);
6583
6584                 if deliver_bs_raa {
6585                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa).unwrap();
6586                         // One monitor for the new revocation preimage, one as we generate a commitment for
6587                         // nodes[0] to fail first_payment_hash backwards.
6588                         check_added_monitors!(nodes[1], 2);
6589                 }
6590
6591                 let mut failed_htlcs = HashSet::new();
6592                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6593
6594                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6595                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6596
6597                 let events = nodes[1].node.get_and_clear_pending_events();
6598                 assert_eq!(events.len(), 1);
6599                 match events[0] {
6600                         Event::PaymentFailed { ref payment_hash, .. } => {
6601                                 assert_eq!(*payment_hash, fourth_payment_hash);
6602                         },
6603                         _ => panic!("Unexpected event"),
6604                 }
6605
6606                 if !deliver_bs_raa {
6607                         // If we delivered the RAA already then we already failed first_payment_hash backwards.
6608                         check_added_monitors!(nodes[1], 1);
6609                 }
6610
6611                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6612                 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
6613                 match events[if deliver_bs_raa { 2 } else { 0 }] {
6614                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6615                         _ => panic!("Unexpected event"),
6616                 }
6617                 if deliver_bs_raa {
6618                         match events[0] {
6619                                 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, .. } } => {
6620                                         assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
6621                                         assert_eq!(update_add_htlcs.len(), 1);
6622                                         assert!(update_fulfill_htlcs.is_empty());
6623                                         assert!(update_fail_htlcs.is_empty());
6624                                         assert!(update_fail_malformed_htlcs.is_empty());
6625                                 },
6626                                 _ => panic!("Unexpected event"),
6627                         }
6628                 }
6629                 // Due to the way backwards-failing occurs we do the updates in two steps.
6630                 let updates = match events[1] {
6631                         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, .. } } => {
6632                                 assert!(update_add_htlcs.is_empty());
6633                                 assert_eq!(update_fail_htlcs.len(), 1);
6634                                 assert!(update_fulfill_htlcs.is_empty());
6635                                 assert!(update_fail_malformed_htlcs.is_empty());
6636                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6637
6638                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6639                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
6640                                 check_added_monitors!(nodes[0], 1);
6641                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6642                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6643                                 check_added_monitors!(nodes[1], 1);
6644                                 let bs_second_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6645                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
6646                                 check_added_monitors!(nodes[1], 1);
6647                                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6648                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6649                                 check_added_monitors!(nodes[0], 1);
6650
6651                                 if !deliver_bs_raa {
6652                                         // If we delievered B's RAA we got an unknown preimage error, not something
6653                                         // that we should update our routing table for.
6654                                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6655                                         assert_eq!(events.len(), 1);
6656                                         match events[0] {
6657                                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6658                                                 _ => panic!("Unexpected event"),
6659                                         }
6660                                 }
6661                                 let events = nodes[0].node.get_and_clear_pending_events();
6662                                 assert_eq!(events.len(), 1);
6663                                 match events[0] {
6664                                         Event::PaymentFailed { ref payment_hash, .. } => {
6665                                                 assert!(failed_htlcs.insert(payment_hash.0));
6666                                         },
6667                                         _ => panic!("Unexpected event"),
6668                                 }
6669
6670                                 bs_second_update
6671                         },
6672                         _ => panic!("Unexpected event"),
6673                 };
6674
6675                 assert!(updates.update_add_htlcs.is_empty());
6676                 assert_eq!(updates.update_fail_htlcs.len(), 2);
6677                 assert!(updates.update_fulfill_htlcs.is_empty());
6678                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6679                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6680                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[1]).unwrap();
6681                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6682
6683                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6684                 assert_eq!(events.len(), 2);
6685                 for event in events {
6686                         match event {
6687                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6688                                 _ => panic!("Unexpected event"),
6689                         }
6690                 }
6691
6692                 let events = nodes[0].node.get_and_clear_pending_events();
6693                 assert_eq!(events.len(), 2);
6694                 match events[0] {
6695                         Event::PaymentFailed { ref payment_hash, .. } => {
6696                                 assert!(failed_htlcs.insert(payment_hash.0));
6697                         },
6698                         _ => panic!("Unexpected event"),
6699                 }
6700                 match events[1] {
6701                         Event::PaymentFailed { ref payment_hash, .. } => {
6702                                 assert!(failed_htlcs.insert(payment_hash.0));
6703                         },
6704                         _ => panic!("Unexpected event"),
6705                 }
6706
6707                 assert!(failed_htlcs.contains(&first_payment_hash.0));
6708                 assert!(failed_htlcs.contains(&second_payment_hash.0));
6709                 assert!(failed_htlcs.contains(&third_payment_hash.0));
6710         }
6711
6712         #[test]
6713         fn test_commitment_revoked_fail_backward_exhaustive() {
6714                 do_test_commitment_revoked_fail_backward_exhaustive(false);
6715                 do_test_commitment_revoked_fail_backward_exhaustive(true);
6716         }
6717
6718         #[test]
6719         fn test_htlc_ignore_latest_remote_commitment() {
6720                 // Test that HTLC transactions spending the latest remote commitment transaction are simply
6721                 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
6722                 let nodes = create_network(2);
6723                 create_announced_chan_between_nodes(&nodes, 0, 1);
6724
6725                 route_payment(&nodes[0], &[&nodes[1]], 10000000);
6726                 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
6727                 {
6728                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6729                         assert_eq!(events.len(), 1);
6730                         match events[0] {
6731                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6732                                         assert_eq!(flags & 0b10, 0b10);
6733                                 },
6734                                 _ => panic!("Unexpected event"),
6735                         }
6736                 }
6737
6738                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6739                 assert_eq!(node_txn.len(), 2);
6740
6741                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6742                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6743
6744                 {
6745                         let events = nodes[1].node.get_and_clear_pending_msg_events();
6746                         assert_eq!(events.len(), 1);
6747                         match events[0] {
6748                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6749                                         assert_eq!(flags & 0b10, 0b10);
6750                                 },
6751                                 _ => panic!("Unexpected event"),
6752                         }
6753                 }
6754
6755                 // Duplicate the block_connected call since this may happen due to other listeners
6756                 // registering new transactions
6757                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6758         }
6759
6760         #[test]
6761         fn test_force_close_fail_back() {
6762                 // Check which HTLCs are failed-backwards on channel force-closure
6763                 let mut nodes = create_network(3);
6764                 create_announced_chan_between_nodes(&nodes, 0, 1);
6765                 create_announced_chan_between_nodes(&nodes, 1, 2);
6766
6767                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
6768
6769                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6770
6771                 let mut payment_event = {
6772                         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6773                         check_added_monitors!(nodes[0], 1);
6774
6775                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6776                         assert_eq!(events.len(), 1);
6777                         SendEvent::from_event(events.remove(0))
6778                 };
6779
6780                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6781                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6782
6783                 let events_1 = nodes[1].node.get_and_clear_pending_events();
6784                 assert_eq!(events_1.len(), 1);
6785                 match events_1[0] {
6786                         Event::PendingHTLCsForwardable { .. } => { },
6787                         _ => panic!("Unexpected event"),
6788                 };
6789
6790                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
6791                 nodes[1].node.process_pending_htlc_forwards();
6792
6793                 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6794                 assert_eq!(events_2.len(), 1);
6795                 payment_event = SendEvent::from_event(events_2.remove(0));
6796                 assert_eq!(payment_event.msgs.len(), 1);
6797
6798                 check_added_monitors!(nodes[1], 1);
6799                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6800                 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
6801                 check_added_monitors!(nodes[2], 1);
6802                 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6803
6804                 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
6805                 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
6806                 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
6807
6808                 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
6809                 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6810                 assert_eq!(events_3.len(), 1);
6811                 match events_3[0] {
6812                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6813                                 assert_eq!(flags & 0b10, 0b10);
6814                         },
6815                         _ => panic!("Unexpected event"),
6816                 }
6817
6818                 let tx = {
6819                         let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6820                         // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
6821                         // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
6822                         // back to nodes[1] upon timeout otherwise.
6823                         assert_eq!(node_txn.len(), 1);
6824                         node_txn.remove(0)
6825                 };
6826
6827                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6828                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6829
6830                 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6831                 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
6832                 assert_eq!(events_4.len(), 1);
6833                 match events_4[0] {
6834                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6835                                 assert_eq!(flags & 0b10, 0b10);
6836                         },
6837                         _ => panic!("Unexpected event"),
6838                 }
6839
6840                 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
6841                 {
6842                         let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
6843                         monitors.get_mut(&OutPoint::new(Sha256dHash::from(&payment_event.commitment_msg.channel_id[..]), 0)).unwrap()
6844                                 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
6845                 }
6846                 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6847                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6848                 assert_eq!(node_txn.len(), 1);
6849                 assert_eq!(node_txn[0].input.len(), 1);
6850                 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
6851                 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
6852                 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
6853
6854                 check_spends!(node_txn[0], tx);
6855         }
6856
6857         #[test]
6858         fn test_unconf_chan() {
6859                 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
6860                 let nodes = create_network(2);
6861                 create_announced_chan_between_nodes(&nodes, 0, 1);
6862
6863                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6864                 assert_eq!(channel_state.by_id.len(), 1);
6865                 assert_eq!(channel_state.short_to_id.len(), 1);
6866                 mem::drop(channel_state);
6867
6868                 let mut headers = Vec::new();
6869                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6870                 headers.push(header.clone());
6871                 for _i in 2..100 {
6872                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6873                         headers.push(header.clone());
6874                 }
6875                 while !headers.is_empty() {
6876                         nodes[0].node.block_disconnected(&headers.pop().unwrap());
6877                 }
6878                 {
6879                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6880                         assert_eq!(events.len(), 1);
6881                         match events[0] {
6882                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6883                                         assert_eq!(flags & 0b10, 0b10);
6884                                 },
6885                                 _ => panic!("Unexpected event"),
6886                         }
6887                 }
6888                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6889                 assert_eq!(channel_state.by_id.len(), 0);
6890                 assert_eq!(channel_state.short_to_id.len(), 0);
6891         }
6892
6893         macro_rules! get_chan_reestablish_msgs {
6894                 ($src_node: expr, $dst_node: expr) => {
6895                         {
6896                                 let mut res = Vec::with_capacity(1);
6897                                 for msg in $src_node.node.get_and_clear_pending_msg_events() {
6898                                         if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
6899                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6900                                                 res.push(msg.clone());
6901                                         } else {
6902                                                 panic!("Unexpected event")
6903                                         }
6904                                 }
6905                                 res
6906                         }
6907                 }
6908         }
6909
6910         macro_rules! handle_chan_reestablish_msgs {
6911                 ($src_node: expr, $dst_node: expr) => {
6912                         {
6913                                 let msg_events = $src_node.node.get_and_clear_pending_msg_events();
6914                                 let mut idx = 0;
6915                                 let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
6916                                         idx += 1;
6917                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6918                                         Some(msg.clone())
6919                                 } else {
6920                                         None
6921                                 };
6922
6923                                 let mut revoke_and_ack = None;
6924                                 let mut commitment_update = None;
6925                                 let order = if let Some(ev) = msg_events.get(idx) {
6926                                         idx += 1;
6927                                         match ev {
6928                                                 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6929                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6930                                                         revoke_and_ack = Some(msg.clone());
6931                                                         RAACommitmentOrder::RevokeAndACKFirst
6932                                                 },
6933                                                 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6934                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6935                                                         commitment_update = Some(updates.clone());
6936                                                         RAACommitmentOrder::CommitmentFirst
6937                                                 },
6938                                                 _ => panic!("Unexpected event"),
6939                                         }
6940                                 } else {
6941                                         RAACommitmentOrder::CommitmentFirst
6942                                 };
6943
6944                                 if let Some(ev) = msg_events.get(idx) {
6945                                         match ev {
6946                                                 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6947                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6948                                                         assert!(revoke_and_ack.is_none());
6949                                                         revoke_and_ack = Some(msg.clone());
6950                                                 },
6951                                                 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6952                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6953                                                         assert!(commitment_update.is_none());
6954                                                         commitment_update = Some(updates.clone());
6955                                                 },
6956                                                 _ => panic!("Unexpected event"),
6957                                         }
6958                                 }
6959
6960                                 (funding_locked, revoke_and_ack, commitment_update, order)
6961                         }
6962                 }
6963         }
6964
6965         /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
6966         /// for claims/fails they are separated out.
6967         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)) {
6968                 node_a.node.peer_connected(&node_b.node.get_our_node_id());
6969                 let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
6970                 node_b.node.peer_connected(&node_a.node.get_our_node_id());
6971                 let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
6972
6973                 if send_funding_locked.0 {
6974                         // If a expects a funding_locked, it better not think it has received a revoke_and_ack
6975                         // from b
6976                         for reestablish in reestablish_1.iter() {
6977                                 assert_eq!(reestablish.next_remote_commitment_number, 0);
6978                         }
6979                 }
6980                 if send_funding_locked.1 {
6981                         // If b expects a funding_locked, it better not think it has received a revoke_and_ack
6982                         // from a
6983                         for reestablish in reestablish_2.iter() {
6984                                 assert_eq!(reestablish.next_remote_commitment_number, 0);
6985                         }
6986                 }
6987                 if send_funding_locked.0 || send_funding_locked.1 {
6988                         // If we expect any funding_locked's, both sides better have set
6989                         // next_local_commitment_number to 1
6990                         for reestablish in reestablish_1.iter() {
6991                                 assert_eq!(reestablish.next_local_commitment_number, 1);
6992                         }
6993                         for reestablish in reestablish_2.iter() {
6994                                 assert_eq!(reestablish.next_local_commitment_number, 1);
6995                         }
6996                 }
6997
6998                 let mut resp_1 = Vec::new();
6999                 for msg in reestablish_1 {
7000                         node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg).unwrap();
7001                         resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
7002                 }
7003                 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
7004                         check_added_monitors!(node_b, 1);
7005                 } else {
7006                         check_added_monitors!(node_b, 0);
7007                 }
7008
7009                 let mut resp_2 = Vec::new();
7010                 for msg in reestablish_2 {
7011                         node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg).unwrap();
7012                         resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
7013                 }
7014                 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
7015                         check_added_monitors!(node_a, 1);
7016                 } else {
7017                         check_added_monitors!(node_a, 0);
7018                 }
7019
7020                 // We dont yet support both needing updates, as that would require a different commitment dance:
7021                 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
7022                         (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
7023
7024                 for chan_msgs in resp_1.drain(..) {
7025                         if send_funding_locked.0 {
7026                                 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
7027                                 let announcement_event = node_a.node.get_and_clear_pending_msg_events();
7028                                 if !announcement_event.is_empty() {
7029                                         assert_eq!(announcement_event.len(), 1);
7030                                         if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
7031                                                 //TODO: Test announcement_sigs re-sending
7032                                         } else { panic!("Unexpected event!"); }
7033                                 }
7034                         } else {
7035                                 assert!(chan_msgs.0.is_none());
7036                         }
7037                         if pending_raa.0 {
7038                                 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
7039                                 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
7040                                 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
7041                                 check_added_monitors!(node_a, 1);
7042                         } else {
7043                                 assert!(chan_msgs.1.is_none());
7044                         }
7045                         if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
7046                                 let commitment_update = chan_msgs.2.unwrap();
7047                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
7048                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
7049                                 } else {
7050                                         assert!(commitment_update.update_add_htlcs.is_empty());
7051                                 }
7052                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
7053                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
7054                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
7055                                 for update_add in commitment_update.update_add_htlcs {
7056                                         node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add).unwrap();
7057                                 }
7058                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
7059                                         node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill).unwrap();
7060                                 }
7061                                 for update_fail in commitment_update.update_fail_htlcs {
7062                                         node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail).unwrap();
7063                                 }
7064
7065                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
7066                                         commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
7067                                 } else {
7068                                         node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
7069                                         check_added_monitors!(node_a, 1);
7070                                         let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
7071                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
7072                                         node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7073                                         assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
7074                                         check_added_monitors!(node_b, 1);
7075                                 }
7076                         } else {
7077                                 assert!(chan_msgs.2.is_none());
7078                         }
7079                 }
7080
7081                 for chan_msgs in resp_2.drain(..) {
7082                         if send_funding_locked.1 {
7083                                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
7084                                 let announcement_event = node_b.node.get_and_clear_pending_msg_events();
7085                                 if !announcement_event.is_empty() {
7086                                         assert_eq!(announcement_event.len(), 1);
7087                                         if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
7088                                                 //TODO: Test announcement_sigs re-sending
7089                                         } else { panic!("Unexpected event!"); }
7090                                 }
7091                         } else {
7092                                 assert!(chan_msgs.0.is_none());
7093                         }
7094                         if pending_raa.1 {
7095                                 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
7096                                 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
7097                                 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
7098                                 check_added_monitors!(node_b, 1);
7099                         } else {
7100                                 assert!(chan_msgs.1.is_none());
7101                         }
7102                         if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
7103                                 let commitment_update = chan_msgs.2.unwrap();
7104                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
7105                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
7106                                 }
7107                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
7108                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
7109                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
7110                                 for update_add in commitment_update.update_add_htlcs {
7111                                         node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add).unwrap();
7112                                 }
7113                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
7114                                         node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill).unwrap();
7115                                 }
7116                                 for update_fail in commitment_update.update_fail_htlcs {
7117                                         node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail).unwrap();
7118                                 }
7119
7120                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
7121                                         commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
7122                                 } else {
7123                                         node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
7124                                         check_added_monitors!(node_b, 1);
7125                                         let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
7126                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
7127                                         node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7128                                         assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
7129                                         check_added_monitors!(node_a, 1);
7130                                 }
7131                         } else {
7132                                 assert!(chan_msgs.2.is_none());
7133                         }
7134                 }
7135         }
7136
7137         #[test]
7138         fn test_simple_peer_disconnect() {
7139                 // Test that we can reconnect when there are no lost messages
7140                 let nodes = create_network(3);
7141                 create_announced_chan_between_nodes(&nodes, 0, 1);
7142                 create_announced_chan_between_nodes(&nodes, 1, 2);
7143
7144                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7145                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7146                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7147
7148                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7149                 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7150                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
7151                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
7152
7153                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7154                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7155                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7156
7157                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7158                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7159                 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7160                 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7161
7162                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7163                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7164
7165                 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3);
7166                 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
7167
7168                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
7169                 {
7170                         let events = nodes[0].node.get_and_clear_pending_events();
7171                         assert_eq!(events.len(), 2);
7172                         match events[0] {
7173                                 Event::PaymentSent { payment_preimage } => {
7174                                         assert_eq!(payment_preimage, payment_preimage_3);
7175                                 },
7176                                 _ => panic!("Unexpected event"),
7177                         }
7178                         match events[1] {
7179                                 Event::PaymentFailed { payment_hash, rejected_by_dest } => {
7180                                         assert_eq!(payment_hash, payment_hash_5);
7181                                         assert!(rejected_by_dest);
7182                                 },
7183                                 _ => panic!("Unexpected event"),
7184                         }
7185                 }
7186
7187                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
7188                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
7189         }
7190
7191         fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
7192                 // Test that we can reconnect when in-flight HTLC updates get dropped
7193                 let mut nodes = create_network(2);
7194                 if messages_delivered == 0 {
7195                         create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
7196                         // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
7197                 } else {
7198                         create_announced_chan_between_nodes(&nodes, 0, 1);
7199                 }
7200
7201                 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();
7202                 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7203
7204                 let payment_event = {
7205                         nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
7206                         check_added_monitors!(nodes[0], 1);
7207
7208                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7209                         assert_eq!(events.len(), 1);
7210                         SendEvent::from_event(events.remove(0))
7211                 };
7212                 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
7213
7214                 if messages_delivered < 2 {
7215                         // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
7216                 } else {
7217                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7218                         if messages_delivered >= 3 {
7219                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7220                                 check_added_monitors!(nodes[1], 1);
7221                                 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7222
7223                                 if messages_delivered >= 4 {
7224                                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7225                                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7226                                         check_added_monitors!(nodes[0], 1);
7227
7228                                         if messages_delivered >= 5 {
7229                                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
7230                                                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7231                                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7232                                                 check_added_monitors!(nodes[0], 1);
7233
7234                                                 if messages_delivered >= 6 {
7235                                                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7236                                                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7237                                                         check_added_monitors!(nodes[1], 1);
7238                                                 }
7239                                         }
7240                                 }
7241                         }
7242                 }
7243
7244                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7245                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7246                 if messages_delivered < 3 {
7247                         // Even if the funding_locked messages get exchanged, as long as nothing further was
7248                         // received on either side, both sides will need to resend them.
7249                         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
7250                 } else if messages_delivered == 3 {
7251                         // nodes[0] still wants its RAA + commitment_signed
7252                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
7253                 } else if messages_delivered == 4 {
7254                         // nodes[0] still wants its commitment_signed
7255                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
7256                 } else if messages_delivered == 5 {
7257                         // nodes[1] still wants its final RAA
7258                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
7259                 } else if messages_delivered == 6 {
7260                         // Everything was delivered...
7261                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7262                 }
7263
7264                 let events_1 = nodes[1].node.get_and_clear_pending_events();
7265                 assert_eq!(events_1.len(), 1);
7266                 match events_1[0] {
7267                         Event::PendingHTLCsForwardable { .. } => { },
7268                         _ => panic!("Unexpected event"),
7269                 };
7270
7271                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7272                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7273                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7274
7275                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7276                 nodes[1].node.process_pending_htlc_forwards();
7277
7278                 let events_2 = nodes[1].node.get_and_clear_pending_events();
7279                 assert_eq!(events_2.len(), 1);
7280                 match events_2[0] {
7281                         Event::PaymentReceived { ref payment_hash, amt } => {
7282                                 assert_eq!(payment_hash_1, *payment_hash);
7283                                 assert_eq!(amt, 1000000);
7284                         },
7285                         _ => panic!("Unexpected event"),
7286                 }
7287
7288                 nodes[1].node.claim_funds(payment_preimage_1);
7289                 check_added_monitors!(nodes[1], 1);
7290
7291                 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
7292                 assert_eq!(events_3.len(), 1);
7293                 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
7294                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
7295                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7296                                 assert!(updates.update_add_htlcs.is_empty());
7297                                 assert!(updates.update_fail_htlcs.is_empty());
7298                                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
7299                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
7300                                 assert!(updates.update_fee.is_none());
7301                                 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
7302                         },
7303                         _ => panic!("Unexpected event"),
7304                 };
7305
7306                 if messages_delivered >= 1 {
7307                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc).unwrap();
7308
7309                         let events_4 = nodes[0].node.get_and_clear_pending_events();
7310                         assert_eq!(events_4.len(), 1);
7311                         match events_4[0] {
7312                                 Event::PaymentSent { ref payment_preimage } => {
7313                                         assert_eq!(payment_preimage_1, *payment_preimage);
7314                                 },
7315                                 _ => panic!("Unexpected event"),
7316                         }
7317
7318                         if messages_delivered >= 2 {
7319                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
7320                                 check_added_monitors!(nodes[0], 1);
7321                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7322
7323                                 if messages_delivered >= 3 {
7324                                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7325                                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7326                                         check_added_monitors!(nodes[1], 1);
7327
7328                                         if messages_delivered >= 4 {
7329                                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
7330                                                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7331                                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7332                                                 check_added_monitors!(nodes[1], 1);
7333
7334                                                 if messages_delivered >= 5 {
7335                                                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7336                                                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7337                                                         check_added_monitors!(nodes[0], 1);
7338                                                 }
7339                                         }
7340                                 }
7341                         }
7342                 }
7343
7344                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7345                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7346                 if messages_delivered < 2 {
7347                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
7348                         //TODO: Deduplicate PaymentSent events, then enable this if:
7349                         //if messages_delivered < 1 {
7350                                 let events_4 = nodes[0].node.get_and_clear_pending_events();
7351                                 assert_eq!(events_4.len(), 1);
7352                                 match events_4[0] {
7353                                         Event::PaymentSent { ref payment_preimage } => {
7354                                                 assert_eq!(payment_preimage_1, *payment_preimage);
7355                                         },
7356                                         _ => panic!("Unexpected event"),
7357                                 }
7358                         //}
7359                 } else if messages_delivered == 2 {
7360                         // nodes[0] still wants its RAA + commitment_signed
7361                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
7362                 } else if messages_delivered == 3 {
7363                         // nodes[0] still wants its commitment_signed
7364                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
7365                 } else if messages_delivered == 4 {
7366                         // nodes[1] still wants its final RAA
7367                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
7368                 } else if messages_delivered == 5 {
7369                         // Everything was delivered...
7370                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7371                 }
7372
7373                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7374                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7375                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7376
7377                 // Channel should still work fine...
7378                 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
7379                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7380         }
7381
7382         #[test]
7383         fn test_drop_messages_peer_disconnect_a() {
7384                 do_test_drop_messages_peer_disconnect(0);
7385                 do_test_drop_messages_peer_disconnect(1);
7386                 do_test_drop_messages_peer_disconnect(2);
7387                 do_test_drop_messages_peer_disconnect(3);
7388         }
7389
7390         #[test]
7391         fn test_drop_messages_peer_disconnect_b() {
7392                 do_test_drop_messages_peer_disconnect(4);
7393                 do_test_drop_messages_peer_disconnect(5);
7394                 do_test_drop_messages_peer_disconnect(6);
7395         }
7396
7397         #[test]
7398         fn test_funding_peer_disconnect() {
7399                 // Test that we can lock in our funding tx while disconnected
7400                 let nodes = create_network(2);
7401                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
7402
7403                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7404                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7405
7406                 confirm_transaction(&nodes[0].chain_monitor, &tx, tx.version);
7407                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7408                 assert_eq!(events_1.len(), 1);
7409                 match events_1[0] {
7410                         MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7411                                 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7412                         },
7413                         _ => panic!("Unexpected event"),
7414                 }
7415
7416                 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7417
7418                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7419                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7420
7421                 confirm_transaction(&nodes[1].chain_monitor, &tx, tx.version);
7422                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7423                 assert_eq!(events_2.len(), 2);
7424                 match events_2[0] {
7425                         MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7426                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7427                         },
7428                         _ => panic!("Unexpected event"),
7429                 }
7430                 match events_2[1] {
7431                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ } => {
7432                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7433                         },
7434                         _ => panic!("Unexpected event"),
7435                 }
7436
7437                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7438
7439                 // TODO: We shouldn't need to manually pass list_usable_chanels here once we support
7440                 // rebroadcasting announcement_signatures upon reconnect.
7441
7442                 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();
7443                 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
7444                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
7445         }
7446
7447         #[test]
7448         fn test_drop_messages_peer_disconnect_dual_htlc() {
7449                 // Test that we can handle reconnecting when both sides of a channel have pending
7450                 // commitment_updates when we disconnect.
7451                 let mut nodes = create_network(2);
7452                 create_announced_chan_between_nodes(&nodes, 0, 1);
7453
7454                 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7455
7456                 // Now try to send a second payment which will fail to send
7457                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7458                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7459
7460                 nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
7461                 check_added_monitors!(nodes[0], 1);
7462
7463                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7464                 assert_eq!(events_1.len(), 1);
7465                 match events_1[0] {
7466                         MessageSendEvent::UpdateHTLCs { .. } => {},
7467                         _ => panic!("Unexpected event"),
7468                 }
7469
7470                 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7471                 check_added_monitors!(nodes[1], 1);
7472
7473                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7474                 assert_eq!(events_2.len(), 1);
7475                 match events_2[0] {
7476                         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 } } => {
7477                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7478                                 assert!(update_add_htlcs.is_empty());
7479                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7480                                 assert!(update_fail_htlcs.is_empty());
7481                                 assert!(update_fail_malformed_htlcs.is_empty());
7482                                 assert!(update_fee.is_none());
7483
7484                                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7485                                 let events_3 = nodes[0].node.get_and_clear_pending_events();
7486                                 assert_eq!(events_3.len(), 1);
7487                                 match events_3[0] {
7488                                         Event::PaymentSent { ref payment_preimage } => {
7489                                                 assert_eq!(*payment_preimage, payment_preimage_1);
7490                                         },
7491                                         _ => panic!("Unexpected event"),
7492                                 }
7493
7494                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
7495                                 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7496                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7497                                 check_added_monitors!(nodes[0], 1);
7498                         },
7499                         _ => panic!("Unexpected event"),
7500                 }
7501
7502                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7503                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7504
7505                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7506                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7507                 assert_eq!(reestablish_1.len(), 1);
7508                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7509                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7510                 assert_eq!(reestablish_2.len(), 1);
7511
7512                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7513                 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7514                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7515                 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7516
7517                 assert!(as_resp.0.is_none());
7518                 assert!(bs_resp.0.is_none());
7519
7520                 assert!(bs_resp.1.is_none());
7521                 assert!(bs_resp.2.is_none());
7522
7523                 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7524
7525                 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
7526                 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
7527                 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7528                 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7529                 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
7530                 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();
7531                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7532                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7533                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7534                 check_added_monitors!(nodes[1], 1);
7535
7536                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap();
7537                 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7538                 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
7539                 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
7540                 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
7541                 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
7542                 assert!(bs_second_commitment_signed.update_fee.is_none());
7543                 check_added_monitors!(nodes[1], 1);
7544
7545                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7546                 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7547                 assert!(as_commitment_signed.update_add_htlcs.is_empty());
7548                 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
7549                 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
7550                 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
7551                 assert!(as_commitment_signed.update_fee.is_none());
7552                 check_added_monitors!(nodes[0], 1);
7553
7554                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
7555                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7556                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7557                 check_added_monitors!(nodes[0], 1);
7558
7559                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
7560                 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7561                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7562                 check_added_monitors!(nodes[1], 1);
7563
7564                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7565                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7566                 check_added_monitors!(nodes[1], 1);
7567
7568                 let events_4 = nodes[1].node.get_and_clear_pending_events();
7569                 assert_eq!(events_4.len(), 1);
7570                 match events_4[0] {
7571                         Event::PendingHTLCsForwardable { .. } => { },
7572                         _ => panic!("Unexpected event"),
7573                 };
7574
7575                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7576                 nodes[1].node.process_pending_htlc_forwards();
7577
7578                 let events_5 = nodes[1].node.get_and_clear_pending_events();
7579                 assert_eq!(events_5.len(), 1);
7580                 match events_5[0] {
7581                         Event::PaymentReceived { ref payment_hash, amt: _ } => {
7582                                 assert_eq!(payment_hash_2, *payment_hash);
7583                         },
7584                         _ => panic!("Unexpected event"),
7585                 }
7586
7587                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
7588                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7589                 check_added_monitors!(nodes[0], 1);
7590
7591                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7592         }
7593
7594         #[test]
7595         fn test_simple_monitor_permanent_update_fail() {
7596                 // Test that we handle a simple permanent monitor update failure
7597                 let mut nodes = create_network(2);
7598                 create_announced_chan_between_nodes(&nodes, 0, 1);
7599
7600                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7601                 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7602
7603                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7604                 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route, payment_hash_1) {} else { panic!(); }
7605                 check_added_monitors!(nodes[0], 1);
7606
7607                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7608                 assert_eq!(events_1.len(), 2);
7609                 match events_1[0] {
7610                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7611                         _ => panic!("Unexpected event"),
7612                 };
7613                 match events_1[1] {
7614                         MessageSendEvent::HandleError { node_id, .. } => assert_eq!(node_id, nodes[1].node.get_our_node_id()),
7615                         _ => panic!("Unexpected event"),
7616                 };
7617
7618                 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7619                 // PaymentFailed event
7620
7621                 assert_eq!(nodes[0].node.list_channels().len(), 0);
7622         }
7623
7624         fn do_test_simple_monitor_temporary_update_fail(disconnect: bool) {
7625                 // Test that we can recover from a simple temporary monitor update failure optionally with
7626                 // a disconnect in between
7627                 let mut nodes = create_network(2);
7628                 create_announced_chan_between_nodes(&nodes, 0, 1);
7629
7630                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7631                 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7632
7633                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7634                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_1) {} else { panic!(); }
7635                 check_added_monitors!(nodes[0], 1);
7636
7637                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7638                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7639                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7640
7641                 if disconnect {
7642                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7643                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7644                         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7645                 }
7646
7647                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7648                 nodes[0].node.test_restore_channel_monitor();
7649                 check_added_monitors!(nodes[0], 1);
7650
7651                 let mut events_2 = nodes[0].node.get_and_clear_pending_msg_events();
7652                 assert_eq!(events_2.len(), 1);
7653                 let payment_event = SendEvent::from_event(events_2.pop().unwrap());
7654                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7655                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7656                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7657
7658                 expect_pending_htlcs_forwardable!(nodes[1]);
7659
7660                 let events_3 = nodes[1].node.get_and_clear_pending_events();
7661                 assert_eq!(events_3.len(), 1);
7662                 match events_3[0] {
7663                         Event::PaymentReceived { ref payment_hash, amt } => {
7664                                 assert_eq!(payment_hash_1, *payment_hash);
7665                                 assert_eq!(amt, 1000000);
7666                         },
7667                         _ => panic!("Unexpected event"),
7668                 }
7669
7670                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_1);
7671
7672                 // Now set it to failed again...
7673                 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7674                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7675                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route, payment_hash_2) {} else { panic!(); }
7676                 check_added_monitors!(nodes[0], 1);
7677
7678                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7679                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7680                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7681
7682                 if disconnect {
7683                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7684                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7685                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7686                 }
7687
7688                 // ...and make sure we can force-close a TemporaryFailure channel with a PermanentFailure
7689                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7690                 nodes[0].node.test_restore_channel_monitor();
7691                 check_added_monitors!(nodes[0], 1);
7692
7693                 let events_5 = nodes[0].node.get_and_clear_pending_msg_events();
7694                 assert_eq!(events_5.len(), 1);
7695                 match events_5[0] {
7696                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7697                         _ => panic!("Unexpected event"),
7698                 }
7699
7700                 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7701                 // PaymentFailed event
7702
7703                 assert_eq!(nodes[0].node.list_channels().len(), 0);
7704         }
7705
7706         #[test]
7707         fn test_simple_monitor_temporary_update_fail() {
7708                 do_test_simple_monitor_temporary_update_fail(false);
7709                 do_test_simple_monitor_temporary_update_fail(true);
7710         }
7711
7712         fn do_test_monitor_temporary_update_fail(disconnect_count: usize) {
7713                 let disconnect_flags = 8 | 16;
7714
7715                 // Test that we can recover from a temporary monitor update failure with some in-flight
7716                 // HTLCs going on at the same time potentially with some disconnection thrown in.
7717                 // * First we route a payment, then get a temporary monitor update failure when trying to
7718                 //   route a second payment. We then claim the first payment.
7719                 // * If disconnect_count is set, we will disconnect at this point (which is likely as
7720                 //   TemporaryFailure likely indicates net disconnect which resulted in failing to update
7721                 //   the ChannelMonitor on a watchtower).
7722                 // * If !(disconnect_count & 16) we deliver a update_fulfill_htlc/CS for the first payment
7723                 //   immediately, otherwise we wait sconnect and deliver them via the reconnect
7724                 //   channel_reestablish processing (ie disconnect_count & 16 makes no sense if
7725                 //   disconnect_count & !disconnect_flags is 0).
7726                 // * We then update the channel monitor, reconnecting if disconnect_count is set and walk
7727                 //   through message sending, potentially disconnect/reconnecting multiple times based on
7728                 //   disconnect_count, to get the update_fulfill_htlc through.
7729                 // * We then walk through more message exchanges to get the original update_add_htlc
7730                 //   through, swapping message ordering based on disconnect_count & 8 and optionally
7731                 //   disconnect/reconnecting based on disconnect_count.
7732                 let mut nodes = create_network(2);
7733                 create_announced_chan_between_nodes(&nodes, 0, 1);
7734
7735                 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7736
7737                 // Now try to send a second payment which will fail to send
7738                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7739                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7740
7741                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7742                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_2) {} else { panic!(); }
7743                 check_added_monitors!(nodes[0], 1);
7744
7745                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7746                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7747                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7748
7749                 // Claim the previous payment, which will result in a update_fulfill_htlc/CS from nodes[1]
7750                 // but nodes[0] won't respond since it is frozen.
7751                 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7752                 check_added_monitors!(nodes[1], 1);
7753                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7754                 assert_eq!(events_2.len(), 1);
7755                 let (bs_initial_fulfill, bs_initial_commitment_signed) = match events_2[0] {
7756                         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 } } => {
7757                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7758                                 assert!(update_add_htlcs.is_empty());
7759                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7760                                 assert!(update_fail_htlcs.is_empty());
7761                                 assert!(update_fail_malformed_htlcs.is_empty());
7762                                 assert!(update_fee.is_none());
7763
7764                                 if (disconnect_count & 16) == 0 {
7765                                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7766                                         let events_3 = nodes[0].node.get_and_clear_pending_events();
7767                                         assert_eq!(events_3.len(), 1);
7768                                         match events_3[0] {
7769                                                 Event::PaymentSent { ref payment_preimage } => {
7770                                                         assert_eq!(*payment_preimage, payment_preimage_1);
7771                                                 },
7772                                                 _ => panic!("Unexpected event"),
7773                                         }
7774
7775                                         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) {
7776                                                 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
7777                                         } else { panic!(); }
7778                                 }
7779
7780                                 (update_fulfill_htlcs[0].clone(), commitment_signed.clone())
7781                         },
7782                         _ => panic!("Unexpected event"),
7783                 };
7784
7785                 if disconnect_count & !disconnect_flags > 0 {
7786                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7787                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7788                 }
7789
7790                 // Now fix monitor updating...
7791                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7792                 nodes[0].node.test_restore_channel_monitor();
7793                 check_added_monitors!(nodes[0], 1);
7794
7795                 macro_rules! disconnect_reconnect_peers { () => { {
7796                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7797                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7798
7799                         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7800                         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7801                         assert_eq!(reestablish_1.len(), 1);
7802                         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7803                         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7804                         assert_eq!(reestablish_2.len(), 1);
7805
7806                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7807                         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7808                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7809                         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7810
7811                         assert!(as_resp.0.is_none());
7812                         assert!(bs_resp.0.is_none());
7813
7814                         (reestablish_1, reestablish_2, as_resp, bs_resp)
7815                 } } }
7816
7817                 let (payment_event, initial_revoke_and_ack) = if disconnect_count & !disconnect_flags > 0 {
7818                         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7819                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7820
7821                         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7822                         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7823                         assert_eq!(reestablish_1.len(), 1);
7824                         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7825                         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7826                         assert_eq!(reestablish_2.len(), 1);
7827
7828                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7829                         check_added_monitors!(nodes[0], 0);
7830                         let mut as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7831                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7832                         check_added_monitors!(nodes[1], 0);
7833                         let mut bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7834
7835                         assert!(as_resp.0.is_none());
7836                         assert!(bs_resp.0.is_none());
7837
7838                         assert!(bs_resp.1.is_none());
7839                         if (disconnect_count & 16) == 0 {
7840                                 assert!(bs_resp.2.is_none());
7841
7842                                 assert!(as_resp.1.is_some());
7843                                 assert!(as_resp.2.is_some());
7844                                 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7845                         } else {
7846                                 assert!(bs_resp.2.as_ref().unwrap().update_add_htlcs.is_empty());
7847                                 assert!(bs_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7848                                 assert!(bs_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7849                                 assert!(bs_resp.2.as_ref().unwrap().update_fee.is_none());
7850                                 assert!(bs_resp.2.as_ref().unwrap().update_fulfill_htlcs == vec![bs_initial_fulfill]);
7851                                 assert!(bs_resp.2.as_ref().unwrap().commitment_signed == bs_initial_commitment_signed);
7852
7853                                 assert!(as_resp.1.is_none());
7854
7855                                 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();
7856                                 let events_3 = nodes[0].node.get_and_clear_pending_events();
7857                                 assert_eq!(events_3.len(), 1);
7858                                 match events_3[0] {
7859                                         Event::PaymentSent { ref payment_preimage } => {
7860                                                 assert_eq!(*payment_preimage, payment_preimage_1);
7861                                         },
7862                                         _ => panic!("Unexpected event"),
7863                                 }
7864
7865                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7866                                 let as_resp_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7867                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7868                                 check_added_monitors!(nodes[0], 1);
7869
7870                                 as_resp.1 = Some(as_resp_raa);
7871                                 bs_resp.2 = None;
7872                         }
7873
7874                         if disconnect_count & !disconnect_flags > 1 {
7875                                 let (second_reestablish_1, second_reestablish_2, second_as_resp, second_bs_resp) = disconnect_reconnect_peers!();
7876
7877                                 if (disconnect_count & 16) == 0 {
7878                                         assert!(reestablish_1 == second_reestablish_1);
7879                                         assert!(reestablish_2 == second_reestablish_2);
7880                                 }
7881                                 assert!(as_resp == second_as_resp);
7882                                 assert!(bs_resp == second_bs_resp);
7883                         }
7884
7885                         (SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), as_resp.2.unwrap()), as_resp.1.unwrap())
7886                 } else {
7887                         let mut events_4 = nodes[0].node.get_and_clear_pending_msg_events();
7888                         assert_eq!(events_4.len(), 2);
7889                         (SendEvent::from_event(events_4.remove(0)), match events_4[0] {
7890                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
7891                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7892                                         msg.clone()
7893                                 },
7894                                 _ => panic!("Unexpected event"),
7895                         })
7896                 };
7897
7898                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7899
7900                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7901                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7902                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7903                 // nodes[1] is awaiting an RAA from nodes[0] still so get_event_msg's assert(len == 1) passes
7904                 check_added_monitors!(nodes[1], 1);
7905
7906                 if disconnect_count & !disconnect_flags > 2 {
7907                         let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7908
7909                         assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7910                         assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7911
7912                         assert!(as_resp.2.is_none());
7913                         assert!(bs_resp.2.is_none());
7914                 }
7915
7916                 let as_commitment_update;
7917                 let bs_second_commitment_update;
7918
7919                 macro_rules! handle_bs_raa { () => {
7920                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7921                         as_commitment_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7922                         assert!(as_commitment_update.update_add_htlcs.is_empty());
7923                         assert!(as_commitment_update.update_fulfill_htlcs.is_empty());
7924                         assert!(as_commitment_update.update_fail_htlcs.is_empty());
7925                         assert!(as_commitment_update.update_fail_malformed_htlcs.is_empty());
7926                         assert!(as_commitment_update.update_fee.is_none());
7927                         check_added_monitors!(nodes[0], 1);
7928                 } }
7929
7930                 macro_rules! handle_initial_raa { () => {
7931                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &initial_revoke_and_ack).unwrap();
7932                         bs_second_commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7933                         assert!(bs_second_commitment_update.update_add_htlcs.is_empty());
7934                         assert!(bs_second_commitment_update.update_fulfill_htlcs.is_empty());
7935                         assert!(bs_second_commitment_update.update_fail_htlcs.is_empty());
7936                         assert!(bs_second_commitment_update.update_fail_malformed_htlcs.is_empty());
7937                         assert!(bs_second_commitment_update.update_fee.is_none());
7938                         check_added_monitors!(nodes[1], 1);
7939                 } }
7940
7941                 if (disconnect_count & 8) == 0 {
7942                         handle_bs_raa!();
7943
7944                         if disconnect_count & !disconnect_flags > 3 {
7945                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7946
7947                                 assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7948                                 assert!(bs_resp.1.is_none());
7949
7950                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7951                                 assert!(bs_resp.2.is_none());
7952
7953                                 assert!(as_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7954                         }
7955
7956                         handle_initial_raa!();
7957
7958                         if disconnect_count & !disconnect_flags > 4 {
7959                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7960
7961                                 assert!(as_resp.1.is_none());
7962                                 assert!(bs_resp.1.is_none());
7963
7964                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7965                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7966                         }
7967                 } else {
7968                         handle_initial_raa!();
7969
7970                         if disconnect_count & !disconnect_flags > 3 {
7971                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7972
7973                                 assert!(as_resp.1.is_none());
7974                                 assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7975
7976                                 assert!(as_resp.2.is_none());
7977                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7978
7979                                 assert!(bs_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7980                         }
7981
7982                         handle_bs_raa!();
7983
7984                         if disconnect_count & !disconnect_flags > 4 {
7985                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7986
7987                                 assert!(as_resp.1.is_none());
7988                                 assert!(bs_resp.1.is_none());
7989
7990                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7991                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7992                         }
7993                 }
7994
7995                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_update.commitment_signed).unwrap();
7996                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7997                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7998                 check_added_monitors!(nodes[0], 1);
7999
8000                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_update.commitment_signed).unwrap();
8001                 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
8002                 // No commitment_signed so get_event_msg's assert(len == 1) passes
8003                 check_added_monitors!(nodes[1], 1);
8004
8005                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
8006                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8007                 check_added_monitors!(nodes[1], 1);
8008
8009                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
8010                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8011                 check_added_monitors!(nodes[0], 1);
8012
8013                 expect_pending_htlcs_forwardable!(nodes[1]);
8014
8015                 let events_5 = nodes[1].node.get_and_clear_pending_events();
8016                 assert_eq!(events_5.len(), 1);
8017                 match events_5[0] {
8018                         Event::PaymentReceived { ref payment_hash, amt } => {
8019                                 assert_eq!(payment_hash_2, *payment_hash);
8020                                 assert_eq!(amt, 1000000);
8021                         },
8022                         _ => panic!("Unexpected event"),
8023                 }
8024
8025                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
8026         }
8027
8028         #[test]
8029         fn test_monitor_temporary_update_fail_a() {
8030                 do_test_monitor_temporary_update_fail(0);
8031                 do_test_monitor_temporary_update_fail(1);
8032                 do_test_monitor_temporary_update_fail(2);
8033                 do_test_monitor_temporary_update_fail(3);
8034                 do_test_monitor_temporary_update_fail(4);
8035                 do_test_monitor_temporary_update_fail(5);
8036         }
8037
8038         #[test]
8039         fn test_monitor_temporary_update_fail_b() {
8040                 do_test_monitor_temporary_update_fail(2 | 8);
8041                 do_test_monitor_temporary_update_fail(3 | 8);
8042                 do_test_monitor_temporary_update_fail(4 | 8);
8043                 do_test_monitor_temporary_update_fail(5 | 8);
8044         }
8045
8046         #[test]
8047         fn test_monitor_temporary_update_fail_c() {
8048                 do_test_monitor_temporary_update_fail(1 | 16);
8049                 do_test_monitor_temporary_update_fail(2 | 16);
8050                 do_test_monitor_temporary_update_fail(3 | 16);
8051                 do_test_monitor_temporary_update_fail(2 | 8 | 16);
8052                 do_test_monitor_temporary_update_fail(3 | 8 | 16);
8053         }
8054
8055         #[test]
8056         fn test_monitor_update_fail_cs() {
8057                 // Tests handling of a monitor update failure when processing an incoming commitment_signed
8058                 let mut nodes = create_network(2);
8059                 create_announced_chan_between_nodes(&nodes, 0, 1);
8060
8061                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8062                 let (payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
8063                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
8064                 check_added_monitors!(nodes[0], 1);
8065
8066                 let send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8067                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8068
8069                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8070                 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() {
8071                         assert_eq!(err, "Failed to update ChannelMonitor");
8072                 } else { panic!(); }
8073                 check_added_monitors!(nodes[1], 1);
8074                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8075
8076                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8077                 nodes[1].node.test_restore_channel_monitor();
8078                 check_added_monitors!(nodes[1], 1);
8079                 let responses = nodes[1].node.get_and_clear_pending_msg_events();
8080                 assert_eq!(responses.len(), 2);
8081
8082                 match responses[0] {
8083                         MessageSendEvent::SendRevokeAndACK { ref msg, ref node_id } => {
8084                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8085                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &msg).unwrap();
8086                                 check_added_monitors!(nodes[0], 1);
8087                         },
8088                         _ => panic!("Unexpected event"),
8089                 }
8090                 match responses[1] {
8091                         MessageSendEvent::UpdateHTLCs { ref updates, ref node_id } => {
8092                                 assert!(updates.update_add_htlcs.is_empty());
8093                                 assert!(updates.update_fulfill_htlcs.is_empty());
8094                                 assert!(updates.update_fail_htlcs.is_empty());
8095                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8096                                 assert!(updates.update_fee.is_none());
8097                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8098
8099                                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8100                                 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() {
8101                                         assert_eq!(err, "Failed to update ChannelMonitor");
8102                                 } else { panic!(); }
8103                                 check_added_monitors!(nodes[0], 1);
8104                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8105                         },
8106                         _ => panic!("Unexpected event"),
8107                 }
8108
8109                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
8110                 nodes[0].node.test_restore_channel_monitor();
8111                 check_added_monitors!(nodes[0], 1);
8112
8113                 let final_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8114                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &final_raa).unwrap();
8115                 check_added_monitors!(nodes[1], 1);
8116
8117                 let mut events = nodes[1].node.get_and_clear_pending_events();
8118                 assert_eq!(events.len(), 1);
8119                 match events[0] {
8120                         Event::PendingHTLCsForwardable { .. } => { },
8121                         _ => panic!("Unexpected event"),
8122                 };
8123                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8124                 nodes[1].node.process_pending_htlc_forwards();
8125
8126                 events = nodes[1].node.get_and_clear_pending_events();
8127                 assert_eq!(events.len(), 1);
8128                 match events[0] {
8129                         Event::PaymentReceived { payment_hash, amt } => {
8130                                 assert_eq!(payment_hash, our_payment_hash);
8131                                 assert_eq!(amt, 1000000);
8132                         },
8133                         _ => panic!("Unexpected event"),
8134                 };
8135
8136                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
8137         }
8138
8139         fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) {
8140                 // Tests handling of a monitor update failure when processing an incoming RAA
8141                 let mut nodes = create_network(3);
8142                 create_announced_chan_between_nodes(&nodes, 0, 1);
8143                 create_announced_chan_between_nodes(&nodes, 1, 2);
8144
8145                 // Rebalance a bit so that we can send backwards from 2 to 1.
8146                 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 5000000);
8147
8148                 // Route a first payment that we'll fail backwards
8149                 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
8150
8151                 // Fail the payment backwards, failing the monitor update on nodes[1]'s receipt of the RAA
8152                 assert!(nodes[2].node.fail_htlc_backwards(&payment_hash_1, PaymentFailReason::PreimageUnknown));
8153                 check_added_monitors!(nodes[2], 1);
8154
8155                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8156                 assert!(updates.update_add_htlcs.is_empty());
8157                 assert!(updates.update_fulfill_htlcs.is_empty());
8158                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8159                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8160                 assert!(updates.update_fee.is_none());
8161                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
8162
8163                 let bs_revoke_and_ack = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
8164                 check_added_monitors!(nodes[0], 0);
8165
8166                 // While the second channel is AwaitingRAA, forward a second payment to get it into the
8167                 // holding cell.
8168                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
8169                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8170                 nodes[0].node.send_payment(route, payment_hash_2).unwrap();
8171                 check_added_monitors!(nodes[0], 1);
8172
8173                 let mut send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8174                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8175                 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false);
8176
8177                 let events_1 = nodes[1].node.get_and_clear_pending_events();
8178                 assert_eq!(events_1.len(), 1);
8179                 match events_1[0] {
8180                         Event::PendingHTLCsForwardable { .. } => { },
8181                         _ => panic!("Unexpected event"),
8182                 };
8183
8184                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8185                 nodes[1].node.process_pending_htlc_forwards();
8186                 check_added_monitors!(nodes[1], 0);
8187                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8188
8189                 // Now fail monitor updating.
8190                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8191                 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() {
8192                         assert_eq!(err, "Failed to update ChannelMonitor");
8193                 } else { panic!(); }
8194                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8195                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8196                 check_added_monitors!(nodes[1], 1);
8197
8198                 // Attempt to forward a third payment but fail due to the second channel being unavailable
8199                 // for forwarding.
8200
8201                 let (_, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
8202                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8203                 nodes[0].node.send_payment(route, payment_hash_3).unwrap();
8204                 check_added_monitors!(nodes[0], 1);
8205
8206                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(()); // We succeed in updating the monitor for the first channel
8207                 send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8208                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8209                 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
8210                 check_added_monitors!(nodes[1], 0);
8211
8212                 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8213                 assert_eq!(events_2.len(), 1);
8214                 match events_2.remove(0) {
8215                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
8216                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8217                                 assert!(updates.update_fulfill_htlcs.is_empty());
8218                                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8219                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8220                                 assert!(updates.update_add_htlcs.is_empty());
8221                                 assert!(updates.update_fee.is_none());
8222
8223                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
8224                                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
8225
8226                                 let events = nodes[0].node.get_and_clear_pending_events();
8227                                 assert_eq!(events.len(), 1);
8228                                 if let Event::PaymentFailed { payment_hash, rejected_by_dest } = events[0] {
8229                                         assert_eq!(payment_hash, payment_hash_3);
8230                                         assert!(!rejected_by_dest);
8231                                 } else { panic!("Unexpected event!"); }
8232                         },
8233                         _ => panic!("Unexpected event type!"),
8234                 };
8235
8236                 let (payment_preimage_4, payment_hash_4) = if test_ignore_second_cs {
8237                         // Try to route another payment backwards from 2 to make sure 1 holds off on responding
8238                         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[0]);
8239                         let route = nodes[2].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8240                         nodes[2].node.send_payment(route, payment_hash_4).unwrap();
8241                         check_added_monitors!(nodes[2], 1);
8242
8243                         send_event = SendEvent::from_event(nodes[2].node.get_and_clear_pending_msg_events().remove(0));
8244                         nodes[1].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8245                         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) {
8246                                 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
8247                         } else { panic!(); }
8248                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8249                         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8250                         (Some(payment_preimage_4), Some(payment_hash_4))
8251                 } else { (None, None) };
8252
8253                 // Restore monitor updating, ensuring we immediately get a fail-back update and a
8254                 // update_add update.
8255                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8256                 nodes[1].node.test_restore_channel_monitor();
8257                 check_added_monitors!(nodes[1], 2);
8258
8259                 let mut events_3 = nodes[1].node.get_and_clear_pending_msg_events();
8260                 if test_ignore_second_cs {
8261                         assert_eq!(events_3.len(), 3);
8262                 } else {
8263                         assert_eq!(events_3.len(), 2);
8264                 }
8265
8266                 // Note that the ordering of the events for different nodes is non-prescriptive, though the
8267                 // ordering of the two events that both go to nodes[2] have to stay in the same order.
8268                 let messages_a = match events_3.pop().unwrap() {
8269                         MessageSendEvent::UpdateHTLCs { node_id, mut updates } => {
8270                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8271                                 assert!(updates.update_fulfill_htlcs.is_empty());
8272                                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8273                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8274                                 assert!(updates.update_add_htlcs.is_empty());
8275                                 assert!(updates.update_fee.is_none());
8276                                 (updates.update_fail_htlcs.remove(0), updates.commitment_signed)
8277                         },
8278                         _ => panic!("Unexpected event type!"),
8279                 };
8280                 let raa = if test_ignore_second_cs {
8281                         match events_3.remove(1) {
8282                                 MessageSendEvent::SendRevokeAndACK { node_id, msg } => {
8283                                         assert_eq!(node_id, nodes[2].node.get_our_node_id());
8284                                         Some(msg.clone())
8285                                 },
8286                                 _ => panic!("Unexpected event"),
8287                         }
8288                 } else { None };
8289                 let send_event_b = SendEvent::from_event(events_3.remove(0));
8290                 assert_eq!(send_event_b.node_id, nodes[2].node.get_our_node_id());
8291
8292                 // Now deliver the new messages...
8293
8294                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &messages_a.0).unwrap();
8295                 commitment_signed_dance!(nodes[0], nodes[1], messages_a.1, false);
8296                 let events_4 = nodes[0].node.get_and_clear_pending_events();
8297                 assert_eq!(events_4.len(), 1);
8298                 if let Event::PaymentFailed { payment_hash, rejected_by_dest } = events_4[0] {
8299                         assert_eq!(payment_hash, payment_hash_1);
8300                         assert!(rejected_by_dest);
8301                 } else { panic!("Unexpected event!"); }
8302
8303                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event_b.msgs[0]).unwrap();
8304                 if test_ignore_second_cs {
8305                         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event_b.commitment_msg).unwrap();
8306                         check_added_monitors!(nodes[2], 1);
8307                         let bs_revoke_and_ack = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8308                         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa.unwrap()).unwrap();
8309                         check_added_monitors!(nodes[2], 1);
8310                         let bs_cs = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8311                         assert!(bs_cs.update_add_htlcs.is_empty());
8312                         assert!(bs_cs.update_fail_htlcs.is_empty());
8313                         assert!(bs_cs.update_fail_malformed_htlcs.is_empty());
8314                         assert!(bs_cs.update_fulfill_htlcs.is_empty());
8315                         assert!(bs_cs.update_fee.is_none());
8316
8317                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
8318                         check_added_monitors!(nodes[1], 1);
8319                         let as_cs = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
8320                         assert!(as_cs.update_add_htlcs.is_empty());
8321                         assert!(as_cs.update_fail_htlcs.is_empty());
8322                         assert!(as_cs.update_fail_malformed_htlcs.is_empty());
8323                         assert!(as_cs.update_fulfill_htlcs.is_empty());
8324                         assert!(as_cs.update_fee.is_none());
8325
8326                         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_cs.commitment_signed).unwrap();
8327                         check_added_monitors!(nodes[1], 1);
8328                         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
8329
8330                         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_cs.commitment_signed).unwrap();
8331                         check_added_monitors!(nodes[2], 1);
8332                         let bs_second_raa = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8333
8334                         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
8335                         check_added_monitors!(nodes[2], 1);
8336                         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
8337
8338                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_second_raa).unwrap();
8339                         check_added_monitors!(nodes[1], 1);
8340                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8341                 } else {
8342                         commitment_signed_dance!(nodes[2], nodes[1], send_event_b.commitment_msg, false);
8343                 }
8344
8345                 let events_5 = nodes[2].node.get_and_clear_pending_events();
8346                 assert_eq!(events_5.len(), 1);
8347                 match events_5[0] {
8348                         Event::PendingHTLCsForwardable { .. } => { },
8349                         _ => panic!("Unexpected event"),
8350                 };
8351
8352                 nodes[2].node.channel_state.lock().unwrap().next_forward = Instant::now();
8353                 nodes[2].node.process_pending_htlc_forwards();
8354
8355                 let events_6 = nodes[2].node.get_and_clear_pending_events();
8356                 assert_eq!(events_6.len(), 1);
8357                 match events_6[0] {
8358                         Event::PaymentReceived { payment_hash, .. } => { assert_eq!(payment_hash, payment_hash_2); },
8359                         _ => panic!("Unexpected event"),
8360                 };
8361
8362                 if test_ignore_second_cs {
8363                         let events_7 = nodes[1].node.get_and_clear_pending_events();
8364                         assert_eq!(events_7.len(), 1);
8365                         match events_7[0] {
8366                                 Event::PendingHTLCsForwardable { .. } => { },
8367                                 _ => panic!("Unexpected event"),
8368                         };
8369
8370                         nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8371                         nodes[1].node.process_pending_htlc_forwards();
8372                         check_added_monitors!(nodes[1], 1);
8373
8374                         send_event = SendEvent::from_node(&nodes[1]);
8375                         assert_eq!(send_event.node_id, nodes[0].node.get_our_node_id());
8376                         assert_eq!(send_event.msgs.len(), 1);
8377                         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8378                         commitment_signed_dance!(nodes[0], nodes[1], send_event.commitment_msg, false);
8379
8380                         let events_8 = nodes[0].node.get_and_clear_pending_events();
8381                         assert_eq!(events_8.len(), 1);
8382                         match events_8[0] {
8383                                 Event::PendingHTLCsForwardable { .. } => { },
8384                                 _ => panic!("Unexpected event"),
8385                         };
8386
8387                         nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
8388                         nodes[0].node.process_pending_htlc_forwards();
8389
8390                         let events_9 = nodes[0].node.get_and_clear_pending_events();
8391                         assert_eq!(events_9.len(), 1);
8392                         match events_9[0] {
8393                                 Event::PaymentReceived { payment_hash, .. } => assert_eq!(payment_hash, payment_hash_4.unwrap()),
8394                                 _ => panic!("Unexpected event"),
8395                         };
8396                         claim_payment(&nodes[2], &[&nodes[1], &nodes[0]], payment_preimage_4.unwrap());
8397                 }
8398
8399                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
8400         }
8401
8402         #[test]
8403         fn test_monitor_update_fail_raa() {
8404                 do_test_monitor_update_fail_raa(false);
8405                 do_test_monitor_update_fail_raa(true);
8406         }
8407
8408         #[test]
8409         fn test_monitor_update_fail_reestablish() {
8410                 // Simple test for message retransmission after monitor update failure on
8411                 // channel_reestablish generating a monitor update (which comes from freeing holding cell
8412                 // HTLCs).
8413                 let mut nodes = create_network(3);
8414                 create_announced_chan_between_nodes(&nodes, 0, 1);
8415                 create_announced_chan_between_nodes(&nodes, 1, 2);
8416
8417                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
8418
8419                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8420                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8421
8422                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
8423                 check_added_monitors!(nodes[2], 1);
8424                 let mut updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8425                 assert!(updates.update_add_htlcs.is_empty());
8426                 assert!(updates.update_fail_htlcs.is_empty());
8427                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8428                 assert!(updates.update_fee.is_none());
8429                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8430                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8431                 check_added_monitors!(nodes[1], 1);
8432                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8433                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
8434
8435                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8436                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8437                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8438
8439                 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
8440                 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8441
8442                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
8443
8444                 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() {
8445                         assert_eq!(err, "Failed to update ChannelMonitor");
8446                 } else { panic!(); }
8447                 check_added_monitors!(nodes[1], 1);
8448
8449                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8450                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8451
8452                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8453                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8454
8455                 assert!(as_reestablish == get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()));
8456                 assert!(bs_reestablish == get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id()));
8457
8458                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
8459
8460                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish).unwrap();
8461                 check_added_monitors!(nodes[1], 0);
8462                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8463
8464                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8465                 nodes[1].node.test_restore_channel_monitor();
8466                 check_added_monitors!(nodes[1], 1);
8467
8468                 updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8469                 assert!(updates.update_add_htlcs.is_empty());
8470                 assert!(updates.update_fail_htlcs.is_empty());
8471                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8472                 assert!(updates.update_fee.is_none());
8473                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8474                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8475                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
8476
8477                 let events = nodes[0].node.get_and_clear_pending_events();
8478                 assert_eq!(events.len(), 1);
8479                 match events[0] {
8480                         Event::PaymentSent { payment_preimage, .. } => assert_eq!(payment_preimage, our_payment_preimage),
8481                         _ => panic!("Unexpected event"),
8482                 }
8483         }
8484
8485         #[test]
8486         fn test_invalid_channel_announcement() {
8487                 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
8488                 let secp_ctx = Secp256k1::new();
8489                 let nodes = create_network(2);
8490
8491                 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1]);
8492
8493                 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8494                 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
8495                 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
8496                 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
8497
8498                 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 } );
8499
8500                 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
8501                 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
8502
8503                 let as_network_key = nodes[0].node.get_our_node_id();
8504                 let bs_network_key = nodes[1].node.get_our_node_id();
8505
8506                 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
8507
8508                 let mut chan_announcement;
8509
8510                 macro_rules! dummy_unsigned_msg {
8511                         () => {
8512                                 msgs::UnsignedChannelAnnouncement {
8513                                         features: msgs::GlobalFeatures::new(),
8514                                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
8515                                         short_channel_id: as_chan.get_short_channel_id().unwrap(),
8516                                         node_id_1: if were_node_one { as_network_key } else { bs_network_key },
8517                                         node_id_2: if were_node_one { bs_network_key } else { as_network_key },
8518                                         bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
8519                                         bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
8520                                         excess_data: Vec::new(),
8521                                 };
8522                         }
8523                 }
8524
8525                 macro_rules! sign_msg {
8526                         ($unsigned_msg: expr) => {
8527                                 let msghash = Message::from_slice(&Sha256dHash::from_data(&$unsigned_msg.encode()[..])[..]).unwrap();
8528                                 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
8529                                 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
8530                                 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].node.our_network_key);
8531                                 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].node.our_network_key);
8532                                 chan_announcement = msgs::ChannelAnnouncement {
8533                                         node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
8534                                         node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
8535                                         bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
8536                                         bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
8537                                         contents: $unsigned_msg
8538                                 }
8539                         }
8540                 }
8541
8542                 let unsigned_msg = dummy_unsigned_msg!();
8543                 sign_msg!(unsigned_msg);
8544                 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
8545                 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 } );
8546
8547                 // Configured with Network::Testnet
8548                 let mut unsigned_msg = dummy_unsigned_msg!();
8549                 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
8550                 sign_msg!(unsigned_msg);
8551                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
8552
8553                 let mut unsigned_msg = dummy_unsigned_msg!();
8554                 unsigned_msg.chain_hash = Sha256dHash::from_data(&[1,2,3,4,5,6,7,8,9]);
8555                 sign_msg!(unsigned_msg);
8556                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
8557         }
8558
8559         struct VecWriter(Vec<u8>);
8560         impl Writer for VecWriter {
8561                 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
8562                         self.0.extend_from_slice(buf);
8563                         Ok(())
8564                 }
8565                 fn size_hint(&mut self, size: usize) {
8566                         self.0.reserve_exact(size);
8567                 }
8568         }
8569
8570         #[test]
8571         fn test_no_txn_manager_serialize_deserialize() {
8572                 let mut nodes = create_network(2);
8573
8574                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
8575
8576                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8577
8578                 let nodes_0_serialized = nodes[0].node.encode();
8579                 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8580                 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8581
8582                 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())));
8583                 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8584                 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8585                 assert!(chan_0_monitor_read.is_empty());
8586
8587                 let mut nodes_0_read = &nodes_0_serialized[..];
8588                 let config = UserConfig::new();
8589                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8590                 let (_, nodes_0_deserialized) = {
8591                         let mut channel_monitors = HashMap::new();
8592                         channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8593                         <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8594                                 default_config: config,
8595                                 keys_manager,
8596                                 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8597                                 monitor: nodes[0].chan_monitor.clone(),
8598                                 chain_monitor: nodes[0].chain_monitor.clone(),
8599                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8600                                 logger: Arc::new(test_utils::TestLogger::new()),
8601                                 channel_monitors: &channel_monitors,
8602                         }).unwrap()
8603                 };
8604                 assert!(nodes_0_read.is_empty());
8605
8606                 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8607                 nodes[0].node = Arc::new(nodes_0_deserialized);
8608                 let nodes_0_as_listener: Arc<ChainListener> = nodes[0].node.clone();
8609                 nodes[0].chain_monitor.register_listener(Arc::downgrade(&nodes_0_as_listener));
8610                 assert_eq!(nodes[0].node.list_channels().len(), 1);
8611                 check_added_monitors!(nodes[0], 1);
8612
8613                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8614                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
8615                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8616                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
8617
8618                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
8619                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8620                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
8621                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8622
8623                 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8624                 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8625                 for node in nodes.iter() {
8626                         assert!(node.router.handle_channel_announcement(&announcement).unwrap());
8627                         node.router.handle_channel_update(&as_update).unwrap();
8628                         node.router.handle_channel_update(&bs_update).unwrap();
8629                 }
8630
8631                 send_payment(&nodes[0], &[&nodes[1]], 1000000);
8632         }
8633
8634         #[test]
8635         fn test_simple_manager_serialize_deserialize() {
8636                 let mut nodes = create_network(2);
8637                 create_announced_chan_between_nodes(&nodes, 0, 1);
8638
8639                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8640                 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8641
8642                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8643
8644                 let nodes_0_serialized = nodes[0].node.encode();
8645                 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8646                 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8647
8648                 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())));
8649                 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8650                 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8651                 assert!(chan_0_monitor_read.is_empty());
8652
8653                 let mut nodes_0_read = &nodes_0_serialized[..];
8654                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8655                 let (_, nodes_0_deserialized) = {
8656                         let mut channel_monitors = HashMap::new();
8657                         channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8658                         <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8659                                 default_config: UserConfig::new(),
8660                                 keys_manager,
8661                                 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8662                                 monitor: nodes[0].chan_monitor.clone(),
8663                                 chain_monitor: nodes[0].chain_monitor.clone(),
8664                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8665                                 logger: Arc::new(test_utils::TestLogger::new()),
8666                                 channel_monitors: &channel_monitors,
8667                         }).unwrap()
8668                 };
8669                 assert!(nodes_0_read.is_empty());
8670
8671                 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8672                 nodes[0].node = Arc::new(nodes_0_deserialized);
8673                 check_added_monitors!(nodes[0], 1);
8674
8675                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8676
8677                 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
8678                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
8679         }
8680
8681         #[test]
8682         fn test_manager_serialize_deserialize_inconsistent_monitor() {
8683                 // Test deserializing a ChannelManager with a out-of-date ChannelMonitor
8684                 let mut nodes = create_network(4);
8685                 create_announced_chan_between_nodes(&nodes, 0, 1);
8686                 create_announced_chan_between_nodes(&nodes, 2, 0);
8687                 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3);
8688
8689                 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
8690
8691                 // Serialize the ChannelManager here, but the monitor we keep up-to-date
8692                 let nodes_0_serialized = nodes[0].node.encode();
8693
8694                 route_payment(&nodes[0], &[&nodes[3]], 1000000);
8695                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8696                 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8697                 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8698
8699                 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
8700                 // nodes[3])
8701                 let mut node_0_monitors_serialized = Vec::new();
8702                 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
8703                         let mut writer = VecWriter(Vec::new());
8704                         monitor.1.write_for_disk(&mut writer).unwrap();
8705                         node_0_monitors_serialized.push(writer.0);
8706                 }
8707
8708                 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())));
8709                 let mut node_0_monitors = Vec::new();
8710                 for serialized in node_0_monitors_serialized.iter() {
8711                         let mut read = &serialized[..];
8712                         let (_, monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
8713                         assert!(read.is_empty());
8714                         node_0_monitors.push(monitor);
8715                 }
8716
8717                 let mut nodes_0_read = &nodes_0_serialized[..];
8718                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8719                 let (_, nodes_0_deserialized) = <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8720                         default_config: UserConfig::new(),
8721                         keys_manager,
8722                         fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8723                         monitor: nodes[0].chan_monitor.clone(),
8724                         chain_monitor: nodes[0].chain_monitor.clone(),
8725                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8726                         logger: Arc::new(test_utils::TestLogger::new()),
8727                         channel_monitors: &node_0_monitors.iter().map(|monitor| { (monitor.get_funding_txo().unwrap(), monitor) }).collect(),
8728                 }).unwrap();
8729                 assert!(nodes_0_read.is_empty());
8730
8731                 { // Channel close should result in a commitment tx and an HTLC tx
8732                         let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8733                         assert_eq!(txn.len(), 2);
8734                         assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
8735                         assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
8736                 }
8737
8738                 for monitor in node_0_monitors.drain(..) {
8739                         assert!(nodes[0].chan_monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor).is_ok());
8740                         check_added_monitors!(nodes[0], 1);
8741                 }
8742                 nodes[0].node = Arc::new(nodes_0_deserialized);
8743
8744                 // nodes[1] and nodes[2] have no lost state with nodes[0]...
8745                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8746                 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8747                 //... and we can even still claim the payment!
8748                 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
8749
8750                 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id());
8751                 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8752                 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id());
8753                 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) {
8754                         assert_eq!(msg.channel_id, channel_id);
8755                 } else { panic!("Unexpected result"); }
8756         }
8757
8758         macro_rules! check_spendable_outputs {
8759                 ($node: expr, $der_idx: expr) => {
8760                         {
8761                                 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
8762                                 let mut txn = Vec::new();
8763                                 for event in events {
8764                                         match event {
8765                                                 Event::SpendableOutputs { ref outputs } => {
8766                                                         for outp in outputs {
8767                                                                 match *outp {
8768                                                                         SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
8769                                                                                 let input = TxIn {
8770                                                                                         previous_output: outpoint.clone(),
8771                                                                                         script_sig: Script::new(),
8772                                                                                         sequence: 0,
8773                                                                                         witness: Vec::new(),
8774                                                                                 };
8775                                                                                 let outp = TxOut {
8776                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8777                                                                                         value: output.value,
8778                                                                                 };
8779                                                                                 let mut spend_tx = Transaction {
8780                                                                                         version: 2,
8781                                                                                         lock_time: 0,
8782                                                                                         input: vec![input],
8783                                                                                         output: vec![outp],
8784                                                                                 };
8785                                                                                 let secp_ctx = Secp256k1::new();
8786                                                                                 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
8787                                                                                 let witness_script = Address::p2pkh(&remotepubkey, Network::Testnet).script_pubkey();
8788                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8789                                                                                 let remotesig = secp_ctx.sign(&sighash, key);
8790                                                                                 spend_tx.input[0].witness.push(remotesig.serialize_der(&secp_ctx).to_vec());
8791                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8792                                                                                 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
8793                                                                                 txn.push(spend_tx);
8794                                                                         },
8795                                                                         SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
8796                                                                                 let input = TxIn {
8797                                                                                         previous_output: outpoint.clone(),
8798                                                                                         script_sig: Script::new(),
8799                                                                                         sequence: *to_self_delay as u32,
8800                                                                                         witness: Vec::new(),
8801                                                                                 };
8802                                                                                 let outp = TxOut {
8803                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8804                                                                                         value: output.value,
8805                                                                                 };
8806                                                                                 let mut spend_tx = Transaction {
8807                                                                                         version: 2,
8808                                                                                         lock_time: 0,
8809                                                                                         input: vec![input],
8810                                                                                         output: vec![outp],
8811                                                                                 };
8812                                                                                 let secp_ctx = Secp256k1::new();
8813                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
8814                                                                                 let local_delaysig = secp_ctx.sign(&sighash, key);
8815                                                                                 spend_tx.input[0].witness.push(local_delaysig.serialize_der(&secp_ctx).to_vec());
8816                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8817                                                                                 spend_tx.input[0].witness.push(vec!(0));
8818                                                                                 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
8819                                                                                 txn.push(spend_tx);
8820                                                                         },
8821                                                                         SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
8822                                                                                 let secp_ctx = Secp256k1::new();
8823                                                                                 let input = TxIn {
8824                                                                                         previous_output: outpoint.clone(),
8825                                                                                         script_sig: Script::new(),
8826                                                                                         sequence: 0,
8827                                                                                         witness: Vec::new(),
8828                                                                                 };
8829                                                                                 let outp = TxOut {
8830                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8831                                                                                         value: output.value,
8832                                                                                 };
8833                                                                                 let mut spend_tx = Transaction {
8834                                                                                         version: 2,
8835                                                                                         lock_time: 0,
8836                                                                                         input: vec![input],
8837                                                                                         output: vec![outp.clone()],
8838                                                                                 };
8839                                                                                 let secret = {
8840                                                                                         match ExtendedPrivKey::new_master(&secp_ctx, Network::Testnet, &$node.node_seed) {
8841                                                                                                 Ok(master_key) => {
8842                                                                                                         match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx)) {
8843                                                                                                                 Ok(key) => key,
8844                                                                                                                 Err(_) => panic!("Your RNG is busted"),
8845                                                                                                         }
8846                                                                                                 }
8847                                                                                                 Err(_) => panic!("Your rng is busted"),
8848                                                                                         }
8849                                                                                 };
8850                                                                                 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
8851                                                                                 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
8852                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8853                                                                                 let sig = secp_ctx.sign(&sighash, &secret.secret_key);
8854                                                                                 spend_tx.input[0].witness.push(sig.serialize_der(&secp_ctx).to_vec());
8855                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8856                                                                                 spend_tx.input[0].witness.push(pubkey.serialize().to_vec());
8857                                                                                 txn.push(spend_tx);
8858                                                                         },
8859                                                                 }
8860                                                         }
8861                                                 },
8862                                                 _ => panic!("Unexpected event"),
8863                                         };
8864                                 }
8865                                 txn
8866                         }
8867                 }
8868         }
8869
8870         #[test]
8871         fn test_claim_sizeable_push_msat() {
8872                 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
8873                 let nodes = create_network(2);
8874
8875                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8876                 nodes[1].node.force_close_channel(&chan.2);
8877                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8878                 match events[0] {
8879                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8880                         _ => panic!("Unexpected event"),
8881                 }
8882                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8883                 assert_eq!(node_txn.len(), 1);
8884                 check_spends!(node_txn[0], chan.3.clone());
8885                 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
8886
8887                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8888                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8889                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8890                 assert_eq!(spend_txn.len(), 1);
8891                 check_spends!(spend_txn[0], node_txn[0].clone());
8892         }
8893
8894         #[test]
8895         fn test_claim_on_remote_sizeable_push_msat() {
8896                 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8897                 // to_remote output is encumbered by a P2WPKH
8898
8899                 let nodes = create_network(2);
8900
8901                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8902                 nodes[0].node.force_close_channel(&chan.2);
8903                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8904                 match events[0] {
8905                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8906                         _ => panic!("Unexpected event"),
8907                 }
8908                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8909                 assert_eq!(node_txn.len(), 1);
8910                 check_spends!(node_txn[0], chan.3.clone());
8911                 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
8912
8913                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8914                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8915                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8916                 match events[0] {
8917                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8918                         _ => panic!("Unexpected event"),
8919                 }
8920                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8921                 assert_eq!(spend_txn.len(), 2);
8922                 assert_eq!(spend_txn[0], spend_txn[1]);
8923                 check_spends!(spend_txn[0], node_txn[0].clone());
8924         }
8925
8926         #[test]
8927         fn test_claim_on_remote_revoked_sizeable_push_msat() {
8928                 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8929                 // to_remote output is encumbered by a P2WPKH
8930
8931                 let nodes = create_network(2);
8932
8933                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
8934                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8935                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
8936                 assert_eq!(revoked_local_txn[0].input.len(), 1);
8937                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8938
8939                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8940                 let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8941                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
8942                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8943                 match events[0] {
8944                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8945                         _ => panic!("Unexpected event"),
8946                 }
8947                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8948                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8949                 assert_eq!(spend_txn.len(), 4);
8950                 assert_eq!(spend_txn[0], spend_txn[2]); // to_remote output on revoked remote commitment_tx
8951                 check_spends!(spend_txn[0], revoked_local_txn[0].clone());
8952                 assert_eq!(spend_txn[1], spend_txn[3]); // to_local output on local commitment tx
8953                 check_spends!(spend_txn[1], node_txn[0].clone());
8954         }
8955
8956         #[test]
8957         fn test_static_spendable_outputs_preimage_tx() {
8958                 let nodes = create_network(2);
8959
8960                 // Create some initial channels
8961                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8962
8963                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8964
8965                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8966                 assert_eq!(commitment_tx[0].input.len(), 1);
8967                 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
8968
8969                 // Settle A's commitment tx on B's chain
8970                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8971                 assert!(nodes[1].node.claim_funds(payment_preimage));
8972                 check_added_monitors!(nodes[1], 1);
8973                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
8974                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8975                 match events[0] {
8976                         MessageSendEvent::UpdateHTLCs { .. } => {},
8977                         _ => panic!("Unexpected event"),
8978                 }
8979                 match events[1] {
8980                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8981                         _ => panic!("Unexepected event"),
8982                 }
8983
8984                 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
8985                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 1 (local commitment tx), ChannelMonitor: 2 (1 preimage tx) * 2 (block-rescan)
8986                 check_spends!(node_txn[0], commitment_tx[0].clone());
8987                 assert_eq!(node_txn[0], node_txn[2]);
8988                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8989                 check_spends!(node_txn[1], chan_1.3.clone());
8990
8991                 let spend_txn = check_spendable_outputs!(nodes[1], 1); // , 0, 0, 1, 1);
8992                 assert_eq!(spend_txn.len(), 2);
8993                 assert_eq!(spend_txn[0], spend_txn[1]);
8994                 check_spends!(spend_txn[0], node_txn[0].clone());
8995         }
8996
8997         #[test]
8998         fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
8999                 let nodes = create_network(2);
9000
9001                 // Create some initial channels
9002                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9003
9004                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9005                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
9006                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9007                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9008
9009                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9010
9011                 let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9012                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9013                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9014                 match events[0] {
9015                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9016                         _ => panic!("Unexpected event"),
9017                 }
9018                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9019                 assert_eq!(node_txn.len(), 3);
9020                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]);
9021                 assert_eq!(node_txn[0].input.len(), 2);
9022                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
9023
9024                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9025                 assert_eq!(spend_txn.len(), 2);
9026                 assert_eq!(spend_txn[0], spend_txn[1]);
9027                 check_spends!(spend_txn[0], node_txn[0].clone());
9028         }
9029
9030         #[test]
9031         fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
9032                 let nodes = create_network(2);
9033
9034                 // Create some initial channels
9035                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9036
9037                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9038                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9039                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9040                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9041
9042                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9043
9044                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9045                 // A will generate HTLC-Timeout from revoked commitment tx
9046                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9047                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9048                 match events[0] {
9049                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9050                         _ => panic!("Unexpected event"),
9051                 }
9052                 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9053                 assert_eq!(revoked_htlc_txn.len(), 3);
9054                 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
9055                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
9056                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9057                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
9058                 check_spends!(revoked_htlc_txn[1], chan_1.3.clone());
9059
9060                 // B will generate justice tx from A's revoked commitment/HTLC tx
9061                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
9062                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9063                 match events[0] {
9064                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9065                         _ => panic!("Unexpected event"),
9066                 }
9067
9068                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9069                 assert_eq!(node_txn.len(), 4);
9070                 assert_eq!(node_txn[3].input.len(), 1);
9071                 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
9072
9073                 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
9074                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9075                 assert_eq!(spend_txn.len(), 3);
9076                 assert_eq!(spend_txn[0], spend_txn[1]);
9077                 check_spends!(spend_txn[0], node_txn[0].clone());
9078                 check_spends!(spend_txn[2], node_txn[3].clone());
9079         }
9080
9081         #[test]
9082         fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
9083                 let nodes = create_network(2);
9084
9085                 // Create some initial channels
9086                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9087
9088                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9089                 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9090                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9091                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9092
9093                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9094
9095                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9096                 // B will generate HTLC-Success from revoked commitment tx
9097                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9098                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9099                 match events[0] {
9100                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9101                         _ => panic!("Unexpected event"),
9102                 }
9103                 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9104
9105                 assert_eq!(revoked_htlc_txn.len(), 3);
9106                 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
9107                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
9108                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9109                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
9110
9111                 // A will generate justice tx from B's revoked commitment/HTLC tx
9112                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
9113                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9114                 match events[0] {
9115                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9116                         _ => panic!("Unexpected event"),
9117                 }
9118
9119                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9120                 assert_eq!(node_txn.len(), 4);
9121                 assert_eq!(node_txn[3].input.len(), 1);
9122                 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
9123
9124                 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
9125                 let spend_txn = check_spendable_outputs!(nodes[0], 1);
9126                 assert_eq!(spend_txn.len(), 5);
9127                 assert_eq!(spend_txn[0], spend_txn[2]);
9128                 assert_eq!(spend_txn[1], spend_txn[3]);
9129                 check_spends!(spend_txn[0], revoked_local_txn[0].clone()); // spending to_remote output from revoked local tx
9130                 check_spends!(spend_txn[1], node_txn[2].clone()); // spending justice tx output from revoked local tx htlc received output
9131                 check_spends!(spend_txn[4], node_txn[3].clone()); // spending justice tx output on htlc success tx
9132         }
9133
9134         #[test]
9135         fn test_onchain_to_onchain_claim() {
9136                 // Test that in case of channel closure, we detect the state of output thanks to
9137                 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
9138                 // First, have C claim an HTLC against its own latest commitment transaction.
9139                 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
9140                 // channel.
9141                 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
9142                 // gets broadcast.
9143
9144                 let nodes = create_network(3);
9145
9146                 // Create some initial channels
9147                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9148                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
9149
9150                 // Rebalance the network a bit by relaying one payment through all the channels ...
9151                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
9152                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
9153
9154                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
9155                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9156                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
9157                 check_spends!(commitment_tx[0], chan_2.3.clone());
9158                 nodes[2].node.claim_funds(payment_preimage);
9159                 check_added_monitors!(nodes[2], 1);
9160                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9161                 assert!(updates.update_add_htlcs.is_empty());
9162                 assert!(updates.update_fail_htlcs.is_empty());
9163                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
9164                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9165
9166                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
9167                 let events = nodes[2].node.get_and_clear_pending_msg_events();
9168                 assert_eq!(events.len(), 1);
9169                 match events[0] {
9170                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9171                         _ => panic!("Unexpected event"),
9172                 }
9173
9174                 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
9175                 assert_eq!(c_txn.len(), 3);
9176                 assert_eq!(c_txn[0], c_txn[2]);
9177                 assert_eq!(commitment_tx[0], c_txn[1]);
9178                 check_spends!(c_txn[1], chan_2.3.clone());
9179                 check_spends!(c_txn[2], c_txn[1].clone());
9180                 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
9181                 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9182                 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
9183                 assert_eq!(c_txn[0].lock_time, 0); // Success tx
9184
9185                 // 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
9186                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
9187                 {
9188                         let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9189                         assert_eq!(b_txn.len(), 4);
9190                         assert_eq!(b_txn[0], b_txn[3]);
9191                         check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
9192                         check_spends!(b_txn[2], b_txn[1].clone()); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
9193                         assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9194                         assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
9195                         assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
9196                         check_spends!(b_txn[0], c_txn[1].clone()); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
9197                         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9198                         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
9199                         assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
9200                         b_txn.clear();
9201                 }
9202                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
9203                 check_added_monitors!(nodes[1], 1);
9204                 match msg_events[0] {
9205                         MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
9206                         _ => panic!("Unexpected event"),
9207                 }
9208                 match msg_events[1] {
9209                         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, .. } } => {
9210                                 assert!(update_add_htlcs.is_empty());
9211                                 assert!(update_fail_htlcs.is_empty());
9212                                 assert_eq!(update_fulfill_htlcs.len(), 1);
9213                                 assert!(update_fail_malformed_htlcs.is_empty());
9214                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
9215                         },
9216                         _ => panic!("Unexpected event"),
9217                 };
9218                 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
9219                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9220                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
9221                 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9222                 assert_eq!(b_txn.len(), 3);
9223                 check_spends!(b_txn[1], chan_1.3); // Local commitment tx, issued by ChannelManager
9224                 assert_eq!(b_txn[0], b_txn[2]); // HTLC-Success tx, issued by ChannelMonitor, * 2 due to block rescan
9225                 check_spends!(b_txn[0], commitment_tx[0].clone());
9226                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9227                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
9228                 assert_eq!(b_txn[2].lock_time, 0); // Success tx
9229                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
9230                 match msg_events[0] {
9231                         MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
9232                         _ => panic!("Unexpected event"),
9233                 }
9234         }
9235
9236         #[test]
9237         fn test_duplicate_payment_hash_one_failure_one_success() {
9238                 // Topology : A --> B --> C
9239                 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
9240                 let mut nodes = create_network(3);
9241
9242                 create_announced_chan_between_nodes(&nodes, 0, 1);
9243                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
9244
9245                 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
9246                 *nodes[0].network_payment_count.borrow_mut() -= 1;
9247                 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
9248
9249                 let commitment_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
9250                 assert_eq!(commitment_txn[0].input.len(), 1);
9251                 check_spends!(commitment_txn[0], chan_2.3.clone());
9252
9253                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9254                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
9255                 let htlc_timeout_tx;
9256                 { // Extract one of the two HTLC-Timeout transaction
9257                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9258                         assert_eq!(node_txn.len(), 7);
9259                         assert_eq!(node_txn[0], node_txn[5]);
9260                         assert_eq!(node_txn[1], node_txn[6]);
9261                         check_spends!(node_txn[0], commitment_txn[0].clone());
9262                         assert_eq!(node_txn[0].input.len(), 1);
9263                         check_spends!(node_txn[1], commitment_txn[0].clone());
9264                         assert_eq!(node_txn[1].input.len(), 1);
9265                         assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
9266                         check_spends!(node_txn[2], chan_2.3.clone());
9267                         check_spends!(node_txn[3], node_txn[2].clone());
9268                         check_spends!(node_txn[4], node_txn[2].clone());
9269                         htlc_timeout_tx = node_txn[1].clone();
9270                 }
9271
9272                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9273                 match events[0] {
9274                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9275                         _ => panic!("Unexepected event"),
9276                 }
9277
9278                 nodes[2].node.claim_funds(our_payment_preimage);
9279                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
9280                 check_added_monitors!(nodes[2], 2);
9281                 let events = nodes[2].node.get_and_clear_pending_msg_events();
9282                 match events[0] {
9283                         MessageSendEvent::UpdateHTLCs { .. } => {},
9284                         _ => panic!("Unexpected event"),
9285                 }
9286                 match events[1] {
9287                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9288                         _ => panic!("Unexepected event"),
9289                 }
9290                 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9291                 assert_eq!(htlc_success_txn.len(), 5);
9292                 check_spends!(htlc_success_txn[2], chan_2.3.clone());
9293                 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
9294                 assert_eq!(htlc_success_txn[0].input.len(), 1);
9295                 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9296                 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
9297                 assert_eq!(htlc_success_txn[1].input.len(), 1);
9298                 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9299                 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
9300                 check_spends!(htlc_success_txn[0], commitment_txn[0].clone());
9301                 check_spends!(htlc_success_txn[1], commitment_txn[0].clone());
9302
9303                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
9304                 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9305                 assert!(htlc_updates.update_add_htlcs.is_empty());
9306                 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
9307                 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
9308                 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
9309                 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
9310                 check_added_monitors!(nodes[1], 1);
9311
9312                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]).unwrap();
9313                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9314                 {
9315                         commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
9316                         let events = nodes[0].node.get_and_clear_pending_msg_events();
9317                         assert_eq!(events.len(), 1);
9318                         match events[0] {
9319                                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
9320                                 },
9321                                 _ => { panic!("Unexpected event"); }
9322                         }
9323                 }
9324                 let events = nodes[0].node.get_and_clear_pending_events();
9325                 match events[0] {
9326                         Event::PaymentFailed { ref payment_hash, .. } => {
9327                                 assert_eq!(*payment_hash, duplicate_payment_hash);
9328                         }
9329                         _ => panic!("Unexpected event"),
9330                 }
9331
9332                 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
9333                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
9334                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9335                 assert!(updates.update_add_htlcs.is_empty());
9336                 assert!(updates.update_fail_htlcs.is_empty());
9337                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
9338                 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
9339                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9340                 check_added_monitors!(nodes[1], 1);
9341
9342                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
9343                 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
9344
9345                 let events = nodes[0].node.get_and_clear_pending_events();
9346                 match events[0] {
9347                         Event::PaymentSent { ref payment_preimage } => {
9348                                 assert_eq!(*payment_preimage, our_payment_preimage);
9349                         }
9350                         _ => panic!("Unexpected event"),
9351                 }
9352         }
9353
9354         #[test]
9355         fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
9356                 let nodes = create_network(2);
9357
9358                 // Create some initial channels
9359                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9360
9361                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
9362                 let local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9363                 assert_eq!(local_txn[0].input.len(), 1);
9364                 check_spends!(local_txn[0], chan_1.3.clone());
9365
9366                 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
9367                 nodes[1].node.claim_funds(payment_preimage);
9368                 check_added_monitors!(nodes[1], 1);
9369                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9370                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
9371                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9372                 match events[0] {
9373                         MessageSendEvent::UpdateHTLCs { .. } => {},
9374                         _ => panic!("Unexpected event"),
9375                 }
9376                 match events[1] {
9377                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9378                         _ => panic!("Unexepected event"),
9379                 }
9380                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9381                 assert_eq!(node_txn[0].input.len(), 1);
9382                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9383                 check_spends!(node_txn[0], local_txn[0].clone());
9384
9385                 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
9386                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9387                 assert_eq!(spend_txn.len(), 2);
9388                 check_spends!(spend_txn[0], node_txn[0].clone());
9389                 check_spends!(spend_txn[1], node_txn[2].clone());
9390         }
9391
9392         #[test]
9393         fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
9394                 let nodes = create_network(2);
9395
9396                 // Create some initial channels
9397                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9398
9399                 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
9400                 let local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9401                 assert_eq!(local_txn[0].input.len(), 1);
9402                 check_spends!(local_txn[0], chan_1.3.clone());
9403
9404                 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
9405                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9406                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
9407                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9408                 match events[0] {
9409                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9410                         _ => panic!("Unexepected event"),
9411                 }
9412                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9413                 assert_eq!(node_txn[0].input.len(), 1);
9414                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9415                 check_spends!(node_txn[0], local_txn[0].clone());
9416
9417                 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
9418                 let spend_txn = check_spendable_outputs!(nodes[0], 1);
9419                 assert_eq!(spend_txn.len(), 8);
9420                 assert_eq!(spend_txn[0], spend_txn[2]);
9421                 assert_eq!(spend_txn[0], spend_txn[4]);
9422                 assert_eq!(spend_txn[0], spend_txn[6]);
9423                 assert_eq!(spend_txn[1], spend_txn[3]);
9424                 assert_eq!(spend_txn[1], spend_txn[5]);
9425                 assert_eq!(spend_txn[1], spend_txn[7]);
9426                 check_spends!(spend_txn[0], local_txn[0].clone());
9427                 check_spends!(spend_txn[1], node_txn[0].clone());
9428         }
9429
9430         #[test]
9431         fn test_static_output_closing_tx() {
9432                 let nodes = create_network(2);
9433
9434                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
9435
9436                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
9437                 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
9438
9439                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9440                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
9441                 let spend_txn = check_spendable_outputs!(nodes[0], 2);
9442                 assert_eq!(spend_txn.len(), 1);
9443                 check_spends!(spend_txn[0], closing_tx.clone());
9444
9445                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
9446                 let spend_txn = check_spendable_outputs!(nodes[1], 2);
9447                 assert_eq!(spend_txn.len(), 1);
9448                 check_spends!(spend_txn[0], closing_tx);
9449         }
9450 }