632ae9f037ea6c88451f202029987d5dde723748
[rust-lightning] / src / ln / channelmanager.rs
1 //! The top-level channel management and payment tracking stuff lives here.
2 //!
3 //! The ChannelManager is the main chunk of logic implementing the lightning protocol and is
4 //! responsible for tracking which channels are open, HTLCs are in flight and reestablishing those
5 //! upon reconnect to the relevant peer(s).
6 //!
7 //! It does not manage routing logic (see ln::router for that) nor does it manage constructing
8 //! on-chain transactions (it only monitors the chain to watch for any force-closes that might
9 //! imply it needs to fail HTLCs/payments/channels it manages).
10
11 use bitcoin::blockdata::block::BlockHeader;
12 use bitcoin::blockdata::transaction::Transaction;
13 use bitcoin::blockdata::constants::genesis_block;
14 use bitcoin::network::constants::Network;
15 use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
16
17 use bitcoin_hashes::{Hash, HashEngine};
18 use bitcoin_hashes::hmac::{Hmac, HmacEngine};
19 use bitcoin_hashes::sha256::Hash as Sha256;
20 use bitcoin_hashes::cmp::fixed_time_eq;
21
22 use secp256k1::key::{SecretKey,PublicKey};
23 use secp256k1::{Secp256k1,Message};
24 use secp256k1::ecdh::SharedSecret;
25 use secp256k1;
26
27 use chain::chaininterface::{BroadcasterInterface,ChainListener,ChainWatchInterface,FeeEstimator};
28 use chain::transaction::OutPoint;
29 use ln::channel::{Channel, ChannelError};
30 use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, ManyChannelMonitor, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, HTLC_FAIL_ANTI_REORG_DELAY};
31 use ln::router::{Route,RouteHop};
32 use ln::msgs;
33 use ln::msgs::{ChannelMessageHandler, DecodeError, HandleError};
34 use chain::keysinterface::KeysInterface;
35 use util::config::UserConfig;
36 use util::{byte_utils, events, internal_traits, rng};
37 use util::ser::{Readable, ReadableArgs, Writeable, Writer};
38 use util::chacha20::ChaCha20;
39 use util::logger::Logger;
40 use util::errors::APIError;
41 use util::errors;
42
43 use std::{cmp, ptr, mem};
44 use std::collections::{HashMap, hash_map, HashSet};
45 use std::io::Cursor;
46 use std::sync::{Arc, Mutex, MutexGuard, RwLock};
47 use std::sync::atomic::{AtomicUsize, Ordering};
48 use std::time::{Instant,Duration};
49
50 // We hold various information about HTLC relay in the HTLC objects in Channel itself:
51 //
52 // Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
53 // forward the HTLC with information it will give back to us when it does so, or if it should Fail
54 // the HTLC with the relevant message for the Channel to handle giving to the remote peer.
55 //
56 // When a Channel forwards an HTLC to its peer, it will give us back the PendingForwardHTLCInfo
57 // which we will use to construct an outbound HTLC, with a relevant HTLCSource::PreviousHopData
58 // filled in to indicate where it came from (which we can use to either fail-backwards or fulfill
59 // the HTLC backwards along the relevant path).
60 // Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
61 // our payment, which we can use to decode errors or inform the user that the payment was sent.
62 /// Stores the info we will need to send when we want to forward an HTLC onwards
63 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
64 pub(super) struct PendingForwardHTLCInfo {
65         onion_packet: Option<msgs::OnionPacket>,
66         incoming_shared_secret: [u8; 32],
67         payment_hash: PaymentHash,
68         short_channel_id: u64,
69         amt_to_forward: u64,
70         outgoing_cltv_value: u32,
71 }
72
73 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
74 pub(super) enum HTLCFailureMsg {
75         Relay(msgs::UpdateFailHTLC),
76         Malformed(msgs::UpdateFailMalformedHTLC),
77 }
78
79 /// Stores whether we can't forward an HTLC or relevant forwarding info
80 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
81 pub(super) enum PendingHTLCStatus {
82         Forward(PendingForwardHTLCInfo),
83         Fail(HTLCFailureMsg),
84 }
85
86 /// Tracks the inbound corresponding to an outbound HTLC
87 #[derive(Clone, PartialEq)]
88 pub(super) struct HTLCPreviousHopData {
89         short_channel_id: u64,
90         htlc_id: u64,
91         incoming_packet_shared_secret: [u8; 32],
92 }
93
94 /// Tracks the inbound corresponding to an outbound HTLC
95 #[derive(Clone, PartialEq)]
96 pub(super) enum HTLCSource {
97         PreviousHopData(HTLCPreviousHopData),
98         OutboundRoute {
99                 route: Route,
100                 session_priv: SecretKey,
101                 /// Technically we can recalculate this from the route, but we cache it here to avoid
102                 /// doing a double-pass on route when we get a failure back
103                 first_hop_htlc_msat: u64,
104         },
105 }
106 #[cfg(test)]
107 impl HTLCSource {
108         pub fn dummy() -> Self {
109                 HTLCSource::OutboundRoute {
110                         route: Route { hops: Vec::new() },
111                         session_priv: SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[1; 32]).unwrap(),
112                         first_hop_htlc_msat: 0,
113                 }
114         }
115 }
116
117 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
118 pub(super) enum HTLCFailReason {
119         ErrorPacket {
120                 err: msgs::OnionErrorPacket,
121         },
122         Reason {
123                 failure_code: u16,
124                 data: Vec<u8>,
125         }
126 }
127
128 /// payment_hash type, use to cross-lock hop
129 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
130 pub struct PaymentHash(pub [u8;32]);
131 /// payment_preimage type, use to route payment between hop
132 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
133 pub struct PaymentPreimage(pub [u8;32]);
134
135 type ShutdownResult = (Vec<Transaction>, Vec<(HTLCSource, PaymentHash)>);
136
137 /// Error type returned across the channel_state mutex boundary. When an Err is generated for a
138 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
139 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
140 /// channel_state lock. We then return the set of things that need to be done outside the lock in
141 /// this struct and call handle_error!() on it.
142
143 struct MsgHandleErrInternal {
144         err: msgs::HandleError,
145         shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
146 }
147 impl MsgHandleErrInternal {
148         #[inline]
149         fn send_err_msg_no_close(err: &'static str, channel_id: [u8; 32]) -> Self {
150                 Self {
151                         err: HandleError {
152                                 err,
153                                 action: Some(msgs::ErrorAction::SendErrorMessage {
154                                         msg: msgs::ErrorMessage {
155                                                 channel_id,
156                                                 data: err.to_string()
157                                         },
158                                 }),
159                         },
160                         shutdown_finish: None,
161                 }
162         }
163         #[inline]
164         fn from_no_close(err: msgs::HandleError) -> Self {
165                 Self { err, shutdown_finish: None }
166         }
167         #[inline]
168         fn from_finish_shutdown(err: &'static str, channel_id: [u8; 32], shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
169                 Self {
170                         err: HandleError {
171                                 err,
172                                 action: Some(msgs::ErrorAction::SendErrorMessage {
173                                         msg: msgs::ErrorMessage {
174                                                 channel_id,
175                                                 data: err.to_string()
176                                         },
177                                 }),
178                         },
179                         shutdown_finish: Some((shutdown_res, channel_update)),
180                 }
181         }
182         #[inline]
183         fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
184                 Self {
185                         err: match err {
186                                 ChannelError::Ignore(msg) => HandleError {
187                                         err: msg,
188                                         action: Some(msgs::ErrorAction::IgnoreError),
189                                 },
190                                 ChannelError::Close(msg) => HandleError {
191                                         err: msg,
192                                         action: Some(msgs::ErrorAction::SendErrorMessage {
193                                                 msg: msgs::ErrorMessage {
194                                                         channel_id,
195                                                         data: msg.to_string()
196                                                 },
197                                         }),
198                                 },
199                         },
200                         shutdown_finish: None,
201                 }
202         }
203 }
204
205 /// We hold back HTLCs we intend to relay for a random interval in the range (this, 5*this). This
206 /// provides some limited amount of privacy. Ideally this would range from somewhere like 1 second
207 /// to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly. We could
208 /// probably increase this significantly.
209 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
210
211 struct HTLCForwardInfo {
212         prev_short_channel_id: u64,
213         prev_htlc_id: u64,
214         forward_info: PendingForwardHTLCInfo,
215 }
216
217 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
218 /// be sent in the order they appear in the return value, however sometimes the order needs to be
219 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
220 /// they were originally sent). In those cases, this enum is also returned.
221 #[derive(Clone, PartialEq)]
222 pub(super) enum RAACommitmentOrder {
223         /// Send the CommitmentUpdate messages first
224         CommitmentFirst,
225         /// Send the RevokeAndACK message first
226         RevokeAndACKFirst,
227 }
228
229 struct ChannelHolder {
230         by_id: HashMap<[u8; 32], Channel>,
231         short_to_id: HashMap<u64, [u8; 32]>,
232         next_forward: Instant,
233         /// short channel id -> forward infos. Key of 0 means payments received
234         /// Note that while this is held in the same mutex as the channels themselves, no consistency
235         /// guarantees are made about there existing a channel with the short id here, nor the short
236         /// ids in the PendingForwardHTLCInfo!
237         forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
238         /// Note that while this is held in the same mutex as the channels themselves, no consistency
239         /// guarantees are made about the channels given here actually existing anymore by the time you
240         /// go to read them!
241         claimable_htlcs: HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
242         /// Messages to send to peers - pushed to in the same lock that they are generated in (except
243         /// for broadcast messages, where ordering isn't as strict).
244         pending_msg_events: Vec<events::MessageSendEvent>,
245 }
246 struct MutChannelHolder<'a> {
247         by_id: &'a mut HashMap<[u8; 32], Channel>,
248         short_to_id: &'a mut HashMap<u64, [u8; 32]>,
249         next_forward: &'a mut Instant,
250         forward_htlcs: &'a mut HashMap<u64, Vec<HTLCForwardInfo>>,
251         claimable_htlcs: &'a mut HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
252         pending_msg_events: &'a mut Vec<events::MessageSendEvent>,
253 }
254 impl ChannelHolder {
255         fn borrow_parts(&mut self) -> MutChannelHolder {
256                 MutChannelHolder {
257                         by_id: &mut self.by_id,
258                         short_to_id: &mut self.short_to_id,
259                         next_forward: &mut self.next_forward,
260                         forward_htlcs: &mut self.forward_htlcs,
261                         claimable_htlcs: &mut self.claimable_htlcs,
262                         pending_msg_events: &mut self.pending_msg_events,
263                 }
264         }
265 }
266
267 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
268 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
269
270 /// Manager which keeps track of a number of channels and sends messages to the appropriate
271 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
272 ///
273 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
274 /// to individual Channels.
275 ///
276 /// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
277 /// all peers during write/read (though does not modify this instance, only the instance being
278 /// serialized). This will result in any channels which have not yet exchanged funding_created (ie
279 /// called funding_transaction_generated for outbound channels).
280 ///
281 /// Note that you can be a bit lazier about writing out ChannelManager than you can be with
282 /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
283 /// returning from ManyChannelMonitor::add_update_monitor, with ChannelManagers, writing updates
284 /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during
285 /// the serialization process). If the deserialized version is out-of-date compared to the
286 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
287 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
288 ///
289 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelManager), which
290 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
291 /// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
292 /// block_connected() to step towards your best block) upon deserialization before using the
293 /// object!
294 pub struct ChannelManager {
295         default_configuration: UserConfig,
296         genesis_hash: Sha256dHash,
297         fee_estimator: Arc<FeeEstimator>,
298         monitor: Arc<ManyChannelMonitor>,
299         chain_monitor: Arc<ChainWatchInterface>,
300         tx_broadcaster: Arc<BroadcasterInterface>,
301
302         latest_block_height: AtomicUsize,
303         last_block_hash: Mutex<Sha256dHash>,
304         secp_ctx: Secp256k1<secp256k1::All>,
305
306         channel_state: Mutex<ChannelHolder>,
307         our_network_key: SecretKey,
308
309         pending_events: Mutex<Vec<events::Event>>,
310         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
311         /// Essentially just when we're serializing ourselves out.
312         /// Taken first everywhere where we are making changes before any other locks.
313         total_consistency_lock: RwLock<()>,
314
315         keys_manager: Arc<KeysInterface>,
316
317         logger: Arc<Logger>,
318 }
319
320 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
321 /// HTLC's CLTV. This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
322 /// ie the node we forwarded the payment on to should always have enough room to reliably time out
323 /// the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
324 /// CLTV_CLAIM_BUFFER point (we static assert that its at least 3 blocks more).
325 const CLTV_EXPIRY_DELTA: u16 = 6 * 12; //TODO?
326 const CLTV_FAR_FAR_AWAY: u32 = 6 * 24 * 7; //TODO?
327
328 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + 2*HTLC_FAIL_TIMEOUT_BLOCKS +
329 // HTLC_FAIL_ANTI_REORG_DELAY, ie that if the next-hop peer fails the HTLC within
330 // HTLC_FAIL_TIMEOUT_BLOCKS then we'll still have HTLC_FAIL_TIMEOUT_BLOCKS left to fail it
331 // backwards ourselves before hitting the CLTV_CLAIM_BUFFER point and failing the channel
332 // on-chain to time out the HTLC.
333 #[deny(const_err)]
334 #[allow(dead_code)]
335 const CHECK_CLTV_EXPIRY_SANITY: u32 = CLTV_EXPIRY_DELTA as u32 - 2*HTLC_FAIL_TIMEOUT_BLOCKS - CLTV_CLAIM_BUFFER - HTLC_FAIL_ANTI_REORG_DELAY;
336
337 // Check for ability of an attacker to make us fail on-chain by delaying inbound claim. See
338 // ChannelMontior::would_broadcast_at_height for a description of why this is needed.
339 #[deny(const_err)]
340 #[allow(dead_code)]
341 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = CLTV_EXPIRY_DELTA as u32 - HTLC_FAIL_TIMEOUT_BLOCKS - 2*CLTV_CLAIM_BUFFER;
342
343 macro_rules! secp_call {
344         ( $res: expr, $err: expr ) => {
345                 match $res {
346                         Ok(key) => key,
347                         Err(_) => return Err($err),
348                 }
349         };
350 }
351
352 struct OnionKeys {
353         #[cfg(test)]
354         shared_secret: SharedSecret,
355         #[cfg(test)]
356         blinding_factor: [u8; 32],
357         ephemeral_pubkey: PublicKey,
358         rho: [u8; 32],
359         mu: [u8; 32],
360 }
361
362 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
363 pub struct ChannelDetails {
364         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
365         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
366         /// Note that this means this value is *not* persistent - it can change once during the
367         /// lifetime of the channel.
368         pub channel_id: [u8; 32],
369         /// The position of the funding transaction in the chain. None if the funding transaction has
370         /// not yet been confirmed and the channel fully opened.
371         pub short_channel_id: Option<u64>,
372         /// The node_id of our counterparty
373         pub remote_network_id: PublicKey,
374         /// The value, in satoshis, of this channel as appears in the funding output
375         pub channel_value_satoshis: u64,
376         /// The user_id passed in to create_channel, or 0 if the channel was inbound.
377         pub user_id: u64,
378 }
379
380 macro_rules! handle_error {
381         ($self: ident, $internal: expr, $their_node_id: expr) => {
382                 match $internal {
383                         Ok(msg) => Ok(msg),
384                         Err(MsgHandleErrInternal { err, shutdown_finish }) => {
385                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
386                                         $self.finish_force_close_channel(shutdown_res);
387                                         if let Some(update) = update_option {
388                                                 let mut channel_state = $self.channel_state.lock().unwrap();
389                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
390                                                         msg: update
391                                                 });
392                                         }
393                                 }
394                                 Err(err)
395                         },
396                 }
397         }
398 }
399
400 macro_rules! break_chan_entry {
401         ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
402                 match $res {
403                         Ok(res) => res,
404                         Err(ChannelError::Ignore(msg)) => {
405                                 break Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
406                         },
407                         Err(ChannelError::Close(msg)) => {
408                                 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
409                                 let (channel_id, mut chan) = $entry.remove_entry();
410                                 if let Some(short_id) = chan.get_short_channel_id() {
411                                         $channel_state.short_to_id.remove(&short_id);
412                                 }
413                                 break Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
414                         },
415                 }
416         }
417 }
418
419 macro_rules! try_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                                 return 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                                 return 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! return_monitor_err {
439         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
440                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new())
441         };
442         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $raa_first_dropped_cs: expr) => {
443                 if $action_type != RAACommitmentOrder::RevokeAndACKFirst { panic!("Bad return_monitor_err call!"); }
444                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new(), $raa_first_dropped_cs)
445         };
446         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr) => {
447                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, $failed_forwards, $failed_fails, false)
448         };
449         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr, $raa_first_dropped_cs: expr) => {
450                 match $err {
451                         ChannelMonitorUpdateErr::PermanentFailure => {
452                                 let (channel_id, mut chan) = $entry.remove_entry();
453                                 if let Some(short_id) = chan.get_short_channel_id() {
454                                         $channel_state.short_to_id.remove(&short_id);
455                                 }
456                                 // TODO: $failed_fails is dropped here, which will cause other channels to hit the
457                                 // chain in a confused state! We need to move them into the ChannelMonitor which
458                                 // will be responsible for failing backwards once things confirm on-chain.
459                                 // It's ok that we drop $failed_forwards here - at this point we'd rather they
460                                 // broadcast HTLC-Timeout and pay the associated fees to get their funds back than
461                                 // us bother trying to claim it just to forward on to another peer. If we're
462                                 // splitting hairs we'd prefer to claim payments that were to us, but we haven't
463                                 // given up the preimage yet, so might as well just wait until the payment is
464                                 // retried, avoiding the on-chain fees.
465                                 return Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
466                         },
467                         ChannelMonitorUpdateErr::TemporaryFailure => {
468                                 $entry.get_mut().monitor_update_failed($action_type, $failed_forwards, $failed_fails, $raa_first_dropped_cs);
469                                 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore("Failed to update ChannelMonitor"), *$entry.key()));
470                         },
471                 }
472         }
473 }
474
475 // Does not break in case of TemporaryFailure!
476 macro_rules! maybe_break_monitor_err {
477         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
478                 match $err {
479                         ChannelMonitorUpdateErr::PermanentFailure => {
480                                 let (channel_id, mut chan) = $entry.remove_entry();
481                                 if let Some(short_id) = chan.get_short_channel_id() {
482                                         $channel_state.short_to_id.remove(&short_id);
483                                 }
484                                 break 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, Vec::new(), Vec::new(), false);
488                         },
489                 }
490         }
491 }
492
493 impl ChannelManager {
494         /// Constructs a new ChannelManager to hold several channels and route between them.
495         ///
496         /// This is the main "logic hub" for all channel-related actions, and implements
497         /// ChannelMessageHandler.
498         ///
499         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
500         ///
501         /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
502         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> {
503                 let secp_ctx = Secp256k1::new();
504
505                 let res = Arc::new(ChannelManager {
506                         default_configuration: config.clone(),
507                         genesis_hash: genesis_block(network).header.bitcoin_hash(),
508                         fee_estimator: feeest.clone(),
509                         monitor: monitor.clone(),
510                         chain_monitor,
511                         tx_broadcaster,
512
513                         latest_block_height: AtomicUsize::new(0), //TODO: Get an init value
514                         last_block_hash: Mutex::new(Default::default()),
515                         secp_ctx,
516
517                         channel_state: Mutex::new(ChannelHolder{
518                                 by_id: HashMap::new(),
519                                 short_to_id: HashMap::new(),
520                                 next_forward: Instant::now(),
521                                 forward_htlcs: HashMap::new(),
522                                 claimable_htlcs: HashMap::new(),
523                                 pending_msg_events: Vec::new(),
524                         }),
525                         our_network_key: keys_manager.get_node_secret(),
526
527                         pending_events: Mutex::new(Vec::new()),
528                         total_consistency_lock: RwLock::new(()),
529
530                         keys_manager,
531
532                         logger,
533                 });
534                 let weak_res = Arc::downgrade(&res);
535                 res.chain_monitor.register_listener(weak_res);
536                 Ok(res)
537         }
538
539         /// Creates a new outbound channel to the given remote node and with the given value.
540         ///
541         /// user_id will be provided back as user_channel_id in FundingGenerationReady and
542         /// FundingBroadcastSafe events to allow tracking of which events correspond with which
543         /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
544         /// may wish to avoid using 0 for user_id here.
545         ///
546         /// If successful, will generate a SendOpenChannel message event, so you should probably poll
547         /// PeerManager::process_events afterwards.
548         ///
549         /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
550         /// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
551         pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64) -> Result<(), APIError> {
552                 if channel_value_satoshis < 1000 {
553                         return Err(APIError::APIMisuseError { err: "channel_value must be at least 1000 satoshis" });
554                 }
555
556                 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)?;
557                 let res = channel.get_open_channel(self.genesis_hash.clone(), &*self.fee_estimator);
558
559                 let _ = self.total_consistency_lock.read().unwrap();
560                 let mut channel_state = self.channel_state.lock().unwrap();
561                 match channel_state.by_id.entry(channel.channel_id()) {
562                         hash_map::Entry::Occupied(_) => {
563                                 if cfg!(feature = "fuzztarget") {
564                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG" });
565                                 } else {
566                                         panic!("RNG is bad???");
567                                 }
568                         },
569                         hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
570                 }
571                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
572                         node_id: their_network_key,
573                         msg: res,
574                 });
575                 Ok(())
576         }
577
578         /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
579         /// more information.
580         pub fn list_channels(&self) -> Vec<ChannelDetails> {
581                 let channel_state = self.channel_state.lock().unwrap();
582                 let mut res = Vec::with_capacity(channel_state.by_id.len());
583                 for (channel_id, channel) in channel_state.by_id.iter() {
584                         res.push(ChannelDetails {
585                                 channel_id: (*channel_id).clone(),
586                                 short_channel_id: channel.get_short_channel_id(),
587                                 remote_network_id: channel.get_their_node_id(),
588                                 channel_value_satoshis: channel.get_value_satoshis(),
589                                 user_id: channel.get_user_id(),
590                         });
591                 }
592                 res
593         }
594
595         /// Gets the list of usable channels, in random order. Useful as an argument to
596         /// Router::get_route to ensure non-announced channels are used.
597         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
598                 let channel_state = self.channel_state.lock().unwrap();
599                 let mut res = Vec::with_capacity(channel_state.by_id.len());
600                 for (channel_id, channel) in channel_state.by_id.iter() {
601                         // Note we use is_live here instead of usable which leads to somewhat confused
602                         // internal/external nomenclature, but that's ok cause that's probably what the user
603                         // really wanted anyway.
604                         if channel.is_live() {
605                                 res.push(ChannelDetails {
606                                         channel_id: (*channel_id).clone(),
607                                         short_channel_id: channel.get_short_channel_id(),
608                                         remote_network_id: channel.get_their_node_id(),
609                                         channel_value_satoshis: channel.get_value_satoshis(),
610                                         user_id: channel.get_user_id(),
611                                 });
612                         }
613                 }
614                 res
615         }
616
617         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
618         /// will be accepted on the given channel, and after additional timeout/the closing of all
619         /// pending HTLCs, the channel will be closed on chain.
620         ///
621         /// May generate a SendShutdown message event on success, which should be relayed.
622         pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
623                 let _ = self.total_consistency_lock.read().unwrap();
624
625                 let (mut failed_htlcs, chan_option) = {
626                         let mut channel_state_lock = self.channel_state.lock().unwrap();
627                         let channel_state = channel_state_lock.borrow_parts();
628                         match channel_state.by_id.entry(channel_id.clone()) {
629                                 hash_map::Entry::Occupied(mut chan_entry) => {
630                                         let (shutdown_msg, failed_htlcs) = chan_entry.get_mut().get_shutdown()?;
631                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
632                                                 node_id: chan_entry.get().get_their_node_id(),
633                                                 msg: shutdown_msg
634                                         });
635                                         if chan_entry.get().is_shutdown() {
636                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
637                                                         channel_state.short_to_id.remove(&short_id);
638                                                 }
639                                                 (failed_htlcs, Some(chan_entry.remove_entry().1))
640                                         } else { (failed_htlcs, None) }
641                                 },
642                                 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: "No such channel"})
643                         }
644                 };
645                 for htlc_source in failed_htlcs.drain(..) {
646                         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() });
647                 }
648                 let chan_update = if let Some(chan) = chan_option {
649                         if let Ok(update) = self.get_channel_update(&chan) {
650                                 Some(update)
651                         } else { None }
652                 } else { None };
653
654                 if let Some(update) = chan_update {
655                         let mut channel_state = self.channel_state.lock().unwrap();
656                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
657                                 msg: update
658                         });
659                 }
660
661                 Ok(())
662         }
663
664         #[inline]
665         fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
666                 let (local_txn, mut failed_htlcs) = shutdown_res;
667                 log_trace!(self, "Finishing force-closure of channel with {} transactions to broadcast and {} HTLCs to fail", local_txn.len(), failed_htlcs.len());
668                 for htlc_source in failed_htlcs.drain(..) {
669                         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() });
670                 }
671                 for tx in local_txn {
672                         self.tx_broadcaster.broadcast_transaction(&tx);
673                 }
674         }
675
676         /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
677         /// the chain and rejecting new HTLCs on the given channel.
678         pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
679                 let _ = self.total_consistency_lock.read().unwrap();
680
681                 let mut chan = {
682                         let mut channel_state_lock = self.channel_state.lock().unwrap();
683                         let channel_state = channel_state_lock.borrow_parts();
684                         if let Some(chan) = channel_state.by_id.remove(channel_id) {
685                                 if let Some(short_id) = chan.get_short_channel_id() {
686                                         channel_state.short_to_id.remove(&short_id);
687                                 }
688                                 chan
689                         } else {
690                                 return;
691                         }
692                 };
693                 log_trace!(self, "Force-closing channel {}", log_bytes!(channel_id[..]));
694                 self.finish_force_close_channel(chan.force_shutdown());
695                 if let Ok(update) = self.get_channel_update(&chan) {
696                         let mut channel_state = self.channel_state.lock().unwrap();
697                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
698                                 msg: update
699                         });
700                 }
701         }
702
703         /// Force close all channels, immediately broadcasting the latest local commitment transaction
704         /// for each to the chain and rejecting new HTLCs on each.
705         pub fn force_close_all_channels(&self) {
706                 for chan in self.list_channels() {
707                         self.force_close_channel(&chan.channel_id);
708                 }
709         }
710
711         #[inline]
712         fn gen_rho_mu_from_shared_secret(shared_secret: &[u8]) -> ([u8; 32], [u8; 32]) {
713                 assert_eq!(shared_secret.len(), 32);
714                 ({
715                         let mut hmac = HmacEngine::<Sha256>::new(&[0x72, 0x68, 0x6f]); // rho
716                         hmac.input(&shared_secret[..]);
717                         Hmac::from_engine(hmac).into_inner()
718                 },
719                 {
720                         let mut hmac = HmacEngine::<Sha256>::new(&[0x6d, 0x75]); // mu
721                         hmac.input(&shared_secret[..]);
722                         Hmac::from_engine(hmac).into_inner()
723                 })
724         }
725
726         #[inline]
727         fn gen_um_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
728                 assert_eq!(shared_secret.len(), 32);
729                 let mut hmac = HmacEngine::<Sha256>::new(&[0x75, 0x6d]); // um
730                 hmac.input(&shared_secret[..]);
731                 Hmac::from_engine(hmac).into_inner()
732         }
733
734         #[inline]
735         fn gen_ammag_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
736                 assert_eq!(shared_secret.len(), 32);
737                 let mut hmac = HmacEngine::<Sha256>::new(&[0x61, 0x6d, 0x6d, 0x61, 0x67]); // ammag
738                 hmac.input(&shared_secret[..]);
739                 Hmac::from_engine(hmac).into_inner()
740         }
741
742         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
743         #[inline]
744         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> {
745                 let mut blinded_priv = session_priv.clone();
746                 let mut blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
747
748                 for hop in route.hops.iter() {
749                         let shared_secret = SharedSecret::new(secp_ctx, &hop.pubkey, &blinded_priv);
750
751                         let mut sha = Sha256::engine();
752                         sha.input(&blinded_pub.serialize()[..]);
753                         sha.input(&shared_secret[..]);
754                         let blinding_factor = Sha256::from_engine(sha).into_inner();
755
756                         let ephemeral_pubkey = blinded_pub;
757
758                         blinded_priv.mul_assign(secp_ctx, &SecretKey::from_slice(secp_ctx, &blinding_factor)?)?;
759                         blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
760
761                         callback(shared_secret, blinding_factor, ephemeral_pubkey, hop);
762                 }
763
764                 Ok(())
765         }
766
767         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
768         fn construct_onion_keys<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey) -> Result<Vec<OnionKeys>, secp256k1::Error> {
769                 let mut res = Vec::with_capacity(route.hops.len());
770
771                 Self::construct_onion_keys_callback(secp_ctx, route, session_priv, |shared_secret, _blinding_factor, ephemeral_pubkey, _| {
772                         let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret[..]);
773
774                         res.push(OnionKeys {
775                                 #[cfg(test)]
776                                 shared_secret,
777                                 #[cfg(test)]
778                                 blinding_factor: _blinding_factor,
779                                 ephemeral_pubkey,
780                                 rho,
781                                 mu,
782                         });
783                 })?;
784
785                 Ok(res)
786         }
787
788         /// returns the hop data, as well as the first-hop value_msat and CLTV value we should send.
789         fn build_onion_payloads(route: &Route, starting_htlc_offset: u32) -> Result<(Vec<msgs::OnionHopData>, u64, u32), APIError> {
790                 let mut cur_value_msat = 0u64;
791                 let mut cur_cltv = starting_htlc_offset;
792                 let mut last_short_channel_id = 0;
793                 let mut res: Vec<msgs::OnionHopData> = Vec::with_capacity(route.hops.len());
794                 internal_traits::test_no_dealloc::<msgs::OnionHopData>(None);
795                 unsafe { res.set_len(route.hops.len()); }
796
797                 for (idx, hop) in route.hops.iter().enumerate().rev() {
798                         // First hop gets special values so that it can check, on receipt, that everything is
799                         // exactly as it should be (and the next hop isn't trying to probe to find out if we're
800                         // the intended recipient).
801                         let value_msat = if cur_value_msat == 0 { hop.fee_msat } else { cur_value_msat };
802                         let cltv = if cur_cltv == starting_htlc_offset { hop.cltv_expiry_delta + starting_htlc_offset } else { cur_cltv };
803                         res[idx] = msgs::OnionHopData {
804                                 realm: 0,
805                                 data: msgs::OnionRealm0HopData {
806                                         short_channel_id: last_short_channel_id,
807                                         amt_to_forward: value_msat,
808                                         outgoing_cltv_value: cltv,
809                                 },
810                                 hmac: [0; 32],
811                         };
812                         cur_value_msat += hop.fee_msat;
813                         if cur_value_msat >= 21000000 * 100000000 * 1000 {
814                                 return Err(APIError::RouteError{err: "Channel fees overflowed?!"});
815                         }
816                         cur_cltv += hop.cltv_expiry_delta as u32;
817                         if cur_cltv >= 500000000 {
818                                 return Err(APIError::RouteError{err: "Channel CLTV overflowed?!"});
819                         }
820                         last_short_channel_id = hop.short_channel_id;
821                 }
822                 Ok((res, cur_value_msat, cur_cltv))
823         }
824
825         #[inline]
826         fn shift_arr_right(arr: &mut [u8; 20*65]) {
827                 unsafe {
828                         ptr::copy(arr[0..].as_ptr(), arr[65..].as_mut_ptr(), 19*65);
829                 }
830                 for i in 0..65 {
831                         arr[i] = 0;
832                 }
833         }
834
835         #[inline]
836         fn xor_bufs(dst: &mut[u8], src: &[u8]) {
837                 assert_eq!(dst.len(), src.len());
838
839                 for i in 0..dst.len() {
840                         dst[i] ^= src[i];
841                 }
842         }
843
844         const ZERO:[u8; 21*65] = [0; 21*65];
845         fn construct_onion_packet(mut payloads: Vec<msgs::OnionHopData>, onion_keys: Vec<OnionKeys>, associated_data: &PaymentHash) -> msgs::OnionPacket {
846                 let mut buf = Vec::with_capacity(21*65);
847                 buf.resize(21*65, 0);
848
849                 let filler = {
850                         let iters = payloads.len() - 1;
851                         let end_len = iters * 65;
852                         let mut res = Vec::with_capacity(end_len);
853                         res.resize(end_len, 0);
854
855                         for (i, keys) in onion_keys.iter().enumerate() {
856                                 if i == payloads.len() - 1 { continue; }
857                                 let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
858                                 chacha.process(&ChannelManager::ZERO, &mut buf); // We don't have a seek function :(
859                                 ChannelManager::xor_bufs(&mut res[0..(i + 1)*65], &buf[(20 - i)*65..21*65]);
860                         }
861                         res
862                 };
863
864                 let mut packet_data = [0; 20*65];
865                 let mut hmac_res = [0; 32];
866
867                 for (i, (payload, keys)) in payloads.iter_mut().zip(onion_keys.iter()).rev().enumerate() {
868                         ChannelManager::shift_arr_right(&mut packet_data);
869                         payload.hmac = hmac_res;
870                         packet_data[0..65].copy_from_slice(&payload.encode()[..]);
871
872                         let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
873                         chacha.process(&packet_data, &mut buf[0..20*65]);
874                         packet_data[..].copy_from_slice(&buf[0..20*65]);
875
876                         if i == 0 {
877                                 packet_data[20*65 - filler.len()..20*65].copy_from_slice(&filler[..]);
878                         }
879
880                         let mut hmac = HmacEngine::<Sha256>::new(&keys.mu);
881                         hmac.input(&packet_data);
882                         hmac.input(&associated_data.0[..]);
883                         hmac_res = Hmac::from_engine(hmac).into_inner();
884                 }
885
886                 msgs::OnionPacket{
887                         version: 0,
888                         public_key: Ok(onion_keys.first().unwrap().ephemeral_pubkey),
889                         hop_data: packet_data,
890                         hmac: hmac_res,
891                 }
892         }
893
894         /// Encrypts a failure packet. raw_packet can either be a
895         /// msgs::DecodedOnionErrorPacket.encode() result or a msgs::OnionErrorPacket.data element.
896         fn encrypt_failure_packet(shared_secret: &[u8], raw_packet: &[u8]) -> msgs::OnionErrorPacket {
897                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
898
899                 let mut packet_crypted = Vec::with_capacity(raw_packet.len());
900                 packet_crypted.resize(raw_packet.len(), 0);
901                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
902                 chacha.process(&raw_packet, &mut packet_crypted[..]);
903                 msgs::OnionErrorPacket {
904                         data: packet_crypted,
905                 }
906         }
907
908         fn build_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::DecodedOnionErrorPacket {
909                 assert_eq!(shared_secret.len(), 32);
910                 assert!(failure_data.len() <= 256 - 2);
911
912                 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
913
914                 let failuremsg = {
915                         let mut res = Vec::with_capacity(2 + failure_data.len());
916                         res.push(((failure_type >> 8) & 0xff) as u8);
917                         res.push(((failure_type >> 0) & 0xff) as u8);
918                         res.extend_from_slice(&failure_data[..]);
919                         res
920                 };
921                 let pad = {
922                         let mut res = Vec::with_capacity(256 - 2 - failure_data.len());
923                         res.resize(256 - 2 - failure_data.len(), 0);
924                         res
925                 };
926                 let mut packet = msgs::DecodedOnionErrorPacket {
927                         hmac: [0; 32],
928                         failuremsg: failuremsg,
929                         pad: pad,
930                 };
931
932                 let mut hmac = HmacEngine::<Sha256>::new(&um);
933                 hmac.input(&packet.encode()[32..]);
934                 packet.hmac = Hmac::from_engine(hmac).into_inner();
935
936                 packet
937         }
938
939         #[inline]
940         fn build_first_hop_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::OnionErrorPacket {
941                 let failure_packet = ChannelManager::build_failure_packet(shared_secret, failure_type, failure_data);
942                 ChannelManager::encrypt_failure_packet(shared_secret, &failure_packet.encode()[..])
943         }
944
945         fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder>) {
946                 macro_rules! return_malformed_err {
947                         ($msg: expr, $err_code: expr) => {
948                                 {
949                                         log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
950                                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
951                                                 channel_id: msg.channel_id,
952                                                 htlc_id: msg.htlc_id,
953                                                 sha256_of_onion: Sha256::hash(&msg.onion_routing_packet.hop_data).into_inner(),
954                                                 failure_code: $err_code,
955                                         })), self.channel_state.lock().unwrap());
956                                 }
957                         }
958                 }
959
960                 if let Err(_) = msg.onion_routing_packet.public_key {
961                         return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
962                 }
963
964                 let shared_secret = {
965                         let mut arr = [0; 32];
966                         arr.copy_from_slice(&SharedSecret::new(&self.secp_ctx, &msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key)[..]);
967                         arr
968                 };
969                 let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
970
971                 if msg.onion_routing_packet.version != 0 {
972                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
973                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
974                         //the hash doesn't really serve any purpuse - in the case of hashing all data, the
975                         //receiving node would have to brute force to figure out which version was put in the
976                         //packet by the node that send us the message, in the case of hashing the hop_data, the
977                         //node knows the HMAC matched, so they already know what is there...
978                         return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
979                 }
980
981
982                 let mut hmac = HmacEngine::<Sha256>::new(&mu);
983                 hmac.input(&msg.onion_routing_packet.hop_data);
984                 hmac.input(&msg.payment_hash.0[..]);
985                 if !fixed_time_eq(&Hmac::from_engine(hmac).into_inner(), &msg.onion_routing_packet.hmac) {
986                         return_malformed_err!("HMAC Check failed", 0x8000 | 0x4000 | 5);
987                 }
988
989                 let mut channel_state = None;
990                 macro_rules! return_err {
991                         ($msg: expr, $err_code: expr, $data: expr) => {
992                                 {
993                                         log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
994                                         if channel_state.is_none() {
995                                                 channel_state = Some(self.channel_state.lock().unwrap());
996                                         }
997                                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
998                                                 channel_id: msg.channel_id,
999                                                 htlc_id: msg.htlc_id,
1000                                                 reason: ChannelManager::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
1001                                         })), channel_state.unwrap());
1002                                 }
1003                         }
1004                 }
1005
1006                 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
1007                 let next_hop_data = {
1008                         let mut decoded = [0; 65];
1009                         chacha.process(&msg.onion_routing_packet.hop_data[0..65], &mut decoded);
1010                         match msgs::OnionHopData::read(&mut Cursor::new(&decoded[..])) {
1011                                 Err(err) => {
1012                                         let error_code = match err {
1013                                                 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
1014                                                 _ => 0x2000 | 2, // Should never happen
1015                                         };
1016                                         return_err!("Unable to decode our hop data", error_code, &[0;0]);
1017                                 },
1018                                 Ok(msg) => msg
1019                         }
1020                 };
1021
1022                 let pending_forward_info = if next_hop_data.hmac == [0; 32] {
1023                                 // OUR PAYMENT!
1024                                 // final_expiry_too_soon
1025                                 if (msg.cltv_expiry as u64) < self.latest_block_height.load(Ordering::Acquire) as u64 + (CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS) as u64 {
1026                                         return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
1027                                 }
1028                                 // final_incorrect_htlc_amount
1029                                 if next_hop_data.data.amt_to_forward > msg.amount_msat {
1030                                         return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
1031                                 }
1032                                 // final_incorrect_cltv_expiry
1033                                 if next_hop_data.data.outgoing_cltv_value != msg.cltv_expiry {
1034                                         return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
1035                                 }
1036
1037                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
1038                                 // message, however that would leak that we are the recipient of this payment, so
1039                                 // instead we stay symmetric with the forwarding case, only responding (after a
1040                                 // delay) once they've send us a commitment_signed!
1041
1042                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1043                                         onion_packet: None,
1044                                         payment_hash: msg.payment_hash.clone(),
1045                                         short_channel_id: 0,
1046                                         incoming_shared_secret: shared_secret,
1047                                         amt_to_forward: next_hop_data.data.amt_to_forward,
1048                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1049                                 })
1050                         } else {
1051                                 let mut new_packet_data = [0; 20*65];
1052                                 chacha.process(&msg.onion_routing_packet.hop_data[65..], &mut new_packet_data[0..19*65]);
1053                                 chacha.process(&ChannelManager::ZERO[0..65], &mut new_packet_data[19*65..]);
1054
1055                                 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
1056
1057                                 let blinding_factor = {
1058                                         let mut sha = Sha256::engine();
1059                                         sha.input(&new_pubkey.serialize()[..]);
1060                                         sha.input(&shared_secret);
1061                                         SecretKey::from_slice(&self.secp_ctx, &Sha256::from_engine(sha).into_inner()).expect("SHA-256 is broken?")
1062                                 };
1063
1064                                 let public_key = if let Err(e) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor) {
1065                                         Err(e)
1066                                 } else { Ok(new_pubkey) };
1067
1068                                 let outgoing_packet = msgs::OnionPacket {
1069                                         version: 0,
1070                                         public_key,
1071                                         hop_data: new_packet_data,
1072                                         hmac: next_hop_data.hmac.clone(),
1073                                 };
1074
1075                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1076                                         onion_packet: Some(outgoing_packet),
1077                                         payment_hash: msg.payment_hash.clone(),
1078                                         short_channel_id: next_hop_data.data.short_channel_id,
1079                                         incoming_shared_secret: shared_secret,
1080                                         amt_to_forward: next_hop_data.data.amt_to_forward,
1081                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1082                                 })
1083                         };
1084
1085                 channel_state = Some(self.channel_state.lock().unwrap());
1086                 if let &PendingHTLCStatus::Forward(PendingForwardHTLCInfo { ref onion_packet, ref short_channel_id, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
1087                         if onion_packet.is_some() { // If short_channel_id is 0 here, we'll reject them in the body here
1088                                 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
1089                                 let forwarding_id = match id_option {
1090                                         None => { // unknown_next_peer
1091                                                 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
1092                                         },
1093                                         Some(id) => id.clone(),
1094                                 };
1095                                 if let Some((err, code, chan_update)) = loop {
1096                                         let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
1097
1098                                         // Note that we could technically not return an error yet here and just hope
1099                                         // that the connection is reestablished or monitor updated by the time we get
1100                                         // around to doing the actual forward, but better to fail early if we can and
1101                                         // hopefully an attacker trying to path-trace payments cannot make this occur
1102                                         // on a small/per-node/per-channel scale.
1103                                         if !chan.is_live() { // channel_disabled
1104                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
1105                                         }
1106                                         if *amt_to_forward < chan.get_their_htlc_minimum_msat() { // amount_below_minimum
1107                                                 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
1108                                         }
1109                                         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) });
1110                                         if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
1111                                                 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())));
1112                                         }
1113                                         if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 { // incorrect_cltv_expiry
1114                                                 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())));
1115                                         }
1116                                         let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1117                                         // We want to have at least HTLC_FAIL_TIMEOUT_BLOCKS to fail prior to going on chain CLAIM_BUFFER blocks before expiration
1118                                         if msg.cltv_expiry <= cur_height + CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS as u32 { // expiry_too_soon
1119                                                 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1120                                         }
1121                                         if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
1122                                                 break Some(("CLTV expiry is too far in the future", 21, None));
1123                                         }
1124                                         break None;
1125                                 }
1126                                 {
1127                                         let mut res = Vec::with_capacity(8 + 128);
1128                                         if let Some(chan_update) = chan_update {
1129                                                 if code == 0x1000 | 11 || code == 0x1000 | 12 {
1130                                                         res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
1131                                                 }
1132                                                 else if code == 0x1000 | 13 {
1133                                                         res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
1134                                                 }
1135                                                 else if code == 0x1000 | 20 {
1136                                                         res.extend_from_slice(&byte_utils::be16_to_array(chan_update.contents.flags));
1137                                                 }
1138                                                 res.extend_from_slice(&chan_update.encode_with_len()[..]);
1139                                         }
1140                                         return_err!(err, code, &res[..]);
1141                                 }
1142                         }
1143                 }
1144
1145                 (pending_forward_info, channel_state.unwrap())
1146         }
1147
1148         /// only fails if the channel does not yet have an assigned short_id
1149         /// May be called with channel_state already locked!
1150         fn get_channel_update(&self, chan: &Channel) -> Result<msgs::ChannelUpdate, HandleError> {
1151                 let short_channel_id = match chan.get_short_channel_id() {
1152                         None => return Err(HandleError{err: "Channel not yet established", action: None}),
1153                         Some(id) => id,
1154                 };
1155
1156                 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_their_node_id().serialize()[..];
1157
1158                 let unsigned = msgs::UnsignedChannelUpdate {
1159                         chain_hash: self.genesis_hash,
1160                         short_channel_id: short_channel_id,
1161                         timestamp: chan.get_channel_update_count(),
1162                         flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
1163                         cltv_expiry_delta: CLTV_EXPIRY_DELTA,
1164                         htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
1165                         fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
1166                         fee_proportional_millionths: chan.get_fee_proportional_millionths(),
1167                         excess_data: Vec::new(),
1168                 };
1169
1170                 let msg_hash = Sha256dHash::from_data(&unsigned.encode()[..]);
1171                 let sig = self.secp_ctx.sign(&Message::from_slice(&msg_hash[..]).unwrap(), &self.our_network_key);
1172
1173                 Ok(msgs::ChannelUpdate {
1174                         signature: sig,
1175                         contents: unsigned
1176                 })
1177         }
1178
1179         /// Sends a payment along a given route.
1180         ///
1181         /// Value parameters are provided via the last hop in route, see documentation for RouteHop
1182         /// fields for more info.
1183         ///
1184         /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
1185         /// payment), we don't do anything to stop you! We always try to ensure that if the provided
1186         /// next hop knows the preimage to payment_hash they can claim an additional amount as
1187         /// specified in the last hop in the route! Thus, you should probably do your own
1188         /// payment_preimage tracking (which you should already be doing as they represent "proof of
1189         /// payment") and prevent double-sends yourself.
1190         ///
1191         /// May generate a SendHTLCs message event on success, which should be relayed.
1192         ///
1193         /// Raises APIError::RoutError when invalid route or forward parameter
1194         /// (cltv_delta, fee, node public key) is specified.
1195         /// Raises APIError::ChannelUnavailable if the next-hop channel is not available for updates
1196         /// (including due to previous monitor update failure or new permanent monitor update failure).
1197         /// Raised APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
1198         /// relevant updates.
1199         ///
1200         /// In case of APIError::RouteError/APIError::ChannelUnavailable, the payment send has failed
1201         /// and you may wish to retry via a different route immediately.
1202         /// In case of APIError::MonitorUpdateFailed, the commitment update has been irrevocably
1203         /// committed on our end and we're just waiting for a monitor update to send it. Do NOT retry
1204         /// the payment via a different route unless you intend to pay twice!
1205         pub fn send_payment(&self, route: Route, payment_hash: PaymentHash) -> Result<(), APIError> {
1206                 if route.hops.len() < 1 || route.hops.len() > 20 {
1207                         return Err(APIError::RouteError{err: "Route didn't go anywhere/had bogus size"});
1208                 }
1209                 let our_node_id = self.get_our_node_id();
1210                 for (idx, hop) in route.hops.iter().enumerate() {
1211                         if idx != route.hops.len() - 1 && hop.pubkey == our_node_id {
1212                                 return Err(APIError::RouteError{err: "Route went through us but wasn't a simple rebalance loop to us"});
1213                         }
1214                 }
1215
1216                 let session_priv = self.keys_manager.get_session_key();
1217
1218                 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1219
1220                 let onion_keys = secp_call!(ChannelManager::construct_onion_keys(&self.secp_ctx, &route, &session_priv),
1221                                 APIError::RouteError{err: "Pubkey along hop was maliciously selected"});
1222                 let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height)?;
1223                 let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
1224
1225                 let _ = self.total_consistency_lock.read().unwrap();
1226
1227                 let err: Result<(), _> = loop {
1228                         let mut channel_lock = self.channel_state.lock().unwrap();
1229
1230                         let id = match channel_lock.short_to_id.get(&route.hops.first().unwrap().short_channel_id) {
1231                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!"}),
1232                                 Some(id) => id.clone(),
1233                         };
1234
1235                         let channel_state = channel_lock.borrow_parts();
1236                         if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) {
1237                                 match {
1238                                         if chan.get().get_their_node_id() != route.hops.first().unwrap().pubkey {
1239                                                 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1240                                         }
1241                                         if !chan.get().is_live() {
1242                                                 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!"});
1243                                         }
1244                                         break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1245                                                 route: route.clone(),
1246                                                 session_priv: session_priv.clone(),
1247                                                 first_hop_htlc_msat: htlc_msat,
1248                                         }, onion_packet), channel_state, chan)
1249                                 } {
1250                                         Some((update_add, commitment_signed, chan_monitor)) => {
1251                                                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1252                                                         maybe_break_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst);
1253                                                         // Note that MonitorUpdateFailed here indicates (per function docs)
1254                                                         // that we will resent the commitment update once we unfree monitor
1255                                                         // updating, so we have to take special care that we don't return
1256                                                         // something else in case we will resend later!
1257                                                         return Err(APIError::MonitorUpdateFailed);
1258                                                 }
1259
1260                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1261                                                         node_id: route.hops.first().unwrap().pubkey,
1262                                                         updates: msgs::CommitmentUpdate {
1263                                                                 update_add_htlcs: vec![update_add],
1264                                                                 update_fulfill_htlcs: Vec::new(),
1265                                                                 update_fail_htlcs: Vec::new(),
1266                                                                 update_fail_malformed_htlcs: Vec::new(),
1267                                                                 update_fee: None,
1268                                                                 commitment_signed,
1269                                                         },
1270                                                 });
1271                                         },
1272                                         None => {},
1273                                 }
1274                         } else { unreachable!(); }
1275                         return Ok(());
1276                 };
1277
1278                 match handle_error!(self, err, route.hops.first().unwrap().pubkey) {
1279                         Ok(_) => unreachable!(),
1280                         Err(e) => {
1281                                 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
1282                                 } else {
1283                                         log_error!(self, "Got bad keys: {}!", e.err);
1284                                         let mut channel_state = self.channel_state.lock().unwrap();
1285                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1286                                                 node_id: route.hops.first().unwrap().pubkey,
1287                                                 action: e.action,
1288                                         });
1289                                 }
1290                                 Err(APIError::ChannelUnavailable { err: e.err })
1291                         },
1292                 }
1293         }
1294
1295         /// Call this upon creation of a funding transaction for the given channel.
1296         ///
1297         /// Note that ALL inputs in the transaction pointed to by funding_txo MUST spend SegWit outputs
1298         /// or your counterparty can steal your funds!
1299         ///
1300         /// Panics if a funding transaction has already been provided for this channel.
1301         ///
1302         /// May panic if the funding_txo is duplicative with some other channel (note that this should
1303         /// be trivially prevented by using unique funding transaction keys per-channel).
1304         pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1305                 let _ = self.total_consistency_lock.read().unwrap();
1306
1307                 let (chan, msg, chan_monitor) = {
1308                         let (res, chan) = {
1309                                 let mut channel_state = self.channel_state.lock().unwrap();
1310                                 match channel_state.by_id.remove(temporary_channel_id) {
1311                                         Some(mut chan) => {
1312                                                 (chan.get_outbound_funding_created(funding_txo)
1313                                                         .map_err(|e| if let ChannelError::Close(msg) = e {
1314                                                                 MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.force_shutdown(), None)
1315                                                         } else { unreachable!(); })
1316                                                 , chan)
1317                                         },
1318                                         None => return
1319                                 }
1320                         };
1321                         match handle_error!(self, res, chan.get_their_node_id()) {
1322                                 Ok(funding_msg) => {
1323                                         (chan, funding_msg.0, funding_msg.1)
1324                                 },
1325                                 Err(e) => {
1326                                         log_error!(self, "Got bad signatures: {}!", e.err);
1327                                         let mut channel_state = self.channel_state.lock().unwrap();
1328                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1329                                                 node_id: chan.get_their_node_id(),
1330                                                 action: e.action,
1331                                         });
1332                                         return;
1333                                 },
1334                         }
1335                 };
1336                 // Because we have exclusive ownership of the channel here we can release the channel_state
1337                 // lock before add_update_monitor
1338                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1339                         unimplemented!();
1340                 }
1341
1342                 let mut channel_state = self.channel_state.lock().unwrap();
1343                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
1344                         node_id: chan.get_their_node_id(),
1345                         msg: msg,
1346                 });
1347                 match channel_state.by_id.entry(chan.channel_id()) {
1348                         hash_map::Entry::Occupied(_) => {
1349                                 panic!("Generated duplicate funding txid?");
1350                         },
1351                         hash_map::Entry::Vacant(e) => {
1352                                 e.insert(chan);
1353                         }
1354                 }
1355         }
1356
1357         fn get_announcement_sigs(&self, chan: &Channel) -> Option<msgs::AnnouncementSignatures> {
1358                 if !chan.should_announce() { return None }
1359
1360                 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1361                         Ok(res) => res,
1362                         Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1363                 };
1364                 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
1365                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1366
1367                 Some(msgs::AnnouncementSignatures {
1368                         channel_id: chan.channel_id(),
1369                         short_channel_id: chan.get_short_channel_id().unwrap(),
1370                         node_signature: our_node_sig,
1371                         bitcoin_signature: our_bitcoin_sig,
1372                 })
1373         }
1374
1375         /// Processes HTLCs which are pending waiting on random forward delay.
1376         ///
1377         /// Should only really ever be called in response to an PendingHTLCsForwardable event.
1378         /// Will likely generate further events.
1379         pub fn process_pending_htlc_forwards(&self) {
1380                 let _ = self.total_consistency_lock.read().unwrap();
1381
1382                 let mut new_events = Vec::new();
1383                 let mut failed_forwards = Vec::new();
1384                 {
1385                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1386                         let channel_state = channel_state_lock.borrow_parts();
1387
1388                         if cfg!(not(feature = "fuzztarget")) && Instant::now() < *channel_state.next_forward {
1389                                 return;
1390                         }
1391
1392                         for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1393                                 if short_chan_id != 0 {
1394                                         let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1395                                                 Some(chan_id) => chan_id.clone(),
1396                                                 None => {
1397                                                         failed_forwards.reserve(pending_forwards.len());
1398                                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1399                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1400                                                                         short_channel_id: prev_short_channel_id,
1401                                                                         htlc_id: prev_htlc_id,
1402                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1403                                                                 });
1404                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
1405                                                         }
1406                                                         continue;
1407                                                 }
1408                                         };
1409                                         let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();
1410
1411                                         let mut add_htlc_msgs = Vec::new();
1412                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1413                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1414                                                         short_channel_id: prev_short_channel_id,
1415                                                         htlc_id: prev_htlc_id,
1416                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1417                                                 });
1418                                                 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()) {
1419                                                         Err(_e) => {
1420                                                                 let chan_update = self.get_channel_update(forward_chan).unwrap();
1421                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x1000 | 7, Some(chan_update)));
1422                                                                 continue;
1423                                                         },
1424                                                         Ok(update_add) => {
1425                                                                 match update_add {
1426                                                                         Some(msg) => { add_htlc_msgs.push(msg); },
1427                                                                         None => {
1428                                                                                 // Nothing to do here...we're waiting on a remote
1429                                                                                 // revoke_and_ack before we can add anymore HTLCs. The Channel
1430                                                                                 // will automatically handle building the update_add_htlc and
1431                                                                                 // commitment_signed messages when we can.
1432                                                                                 // TODO: Do some kind of timer to set the channel as !is_live()
1433                                                                                 // as we don't really want others relying on us relaying through
1434                                                                                 // this channel currently :/.
1435                                                                         }
1436                                                                 }
1437                                                         }
1438                                                 }
1439                                         }
1440
1441                                         if !add_htlc_msgs.is_empty() {
1442                                                 let (commitment_msg, monitor) = match forward_chan.send_commitment() {
1443                                                         Ok(res) => res,
1444                                                         Err(e) => {
1445                                                                 if let ChannelError::Ignore(_) = e {
1446                                                                         panic!("Stated return value requirements in send_commitment() were not met");
1447                                                                 }
1448                                                                 //TODO: Handle...this is bad!
1449                                                                 continue;
1450                                                         },
1451                                                 };
1452                                                 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
1453                                                         unimplemented!();
1454                                                 }
1455                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1456                                                         node_id: forward_chan.get_their_node_id(),
1457                                                         updates: msgs::CommitmentUpdate {
1458                                                                 update_add_htlcs: add_htlc_msgs,
1459                                                                 update_fulfill_htlcs: Vec::new(),
1460                                                                 update_fail_htlcs: Vec::new(),
1461                                                                 update_fail_malformed_htlcs: Vec::new(),
1462                                                                 update_fee: None,
1463                                                                 commitment_signed: commitment_msg,
1464                                                         },
1465                                                 });
1466                                         }
1467                                 } else {
1468                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1469                                                 let prev_hop_data = HTLCPreviousHopData {
1470                                                         short_channel_id: prev_short_channel_id,
1471                                                         htlc_id: prev_htlc_id,
1472                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1473                                                 };
1474                                                 match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
1475                                                         hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(prev_hop_data),
1476                                                         hash_map::Entry::Vacant(entry) => { entry.insert(vec![prev_hop_data]); },
1477                                                 };
1478                                                 new_events.push(events::Event::PaymentReceived {
1479                                                         payment_hash: forward_info.payment_hash,
1480                                                         amt: forward_info.amt_to_forward,
1481                                                 });
1482                                         }
1483                                 }
1484                         }
1485                 }
1486
1487                 for (htlc_source, payment_hash, failure_code, update) in failed_forwards.drain(..) {
1488                         match update {
1489                                 None => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code, data: Vec::new() }),
1490                                 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() }),
1491                         };
1492                 }
1493
1494                 if new_events.is_empty() { return }
1495                 let mut events = self.pending_events.lock().unwrap();
1496                 events.append(&mut new_events);
1497         }
1498
1499         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
1500         /// after a PaymentReceived event.
1501         /// expected_value is the value you expected the payment to be for (not the amount it actually
1502         /// was for from the PaymentReceived event).
1503         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash, expected_value: u64) -> bool {
1504                 let _ = self.total_consistency_lock.read().unwrap();
1505
1506                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1507                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(payment_hash);
1508                 if let Some(mut sources) = removed_source {
1509                         for htlc_with_hash in sources.drain(..) {
1510                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1511                                 self.fail_htlc_backwards_internal(channel_state.take().unwrap(),
1512                                                 HTLCSource::PreviousHopData(htlc_with_hash), payment_hash,
1513                                                 HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: byte_utils::be64_to_array(expected_value).to_vec() });
1514                         }
1515                         true
1516                 } else { false }
1517         }
1518
1519         /// Fails an HTLC backwards to the sender of it to us.
1520         /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
1521         /// There are several callsites that do stupid things like loop over a list of payment_hashes
1522         /// to fail and take the channel_state lock for each iteration (as we take ownership and may
1523         /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
1524         /// still-available channels.
1525         fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
1526                 match source {
1527                         HTLCSource::OutboundRoute { ref route, .. } => {
1528                                 log_trace!(self, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1529                                 mem::drop(channel_state_lock);
1530                                 match &onion_error {
1531                                         &HTLCFailReason::ErrorPacket { ref err } => {
1532 #[cfg(test)]
1533                                                 let (channel_update, payment_retryable, onion_error_code) = self.process_onion_failure(&source, err.data.clone());
1534 #[cfg(not(test))]
1535                                                 let (channel_update, payment_retryable, _) = self.process_onion_failure(&source, err.data.clone());
1536                                                 // TODO: If we decided to blame ourselves (or one of our channels) in
1537                                                 // process_onion_failure we should close that channel as it implies our
1538                                                 // next-hop is needlessly blaming us!
1539                                                 if let Some(update) = channel_update {
1540                                                         self.channel_state.lock().unwrap().pending_msg_events.push(
1541                                                                 events::MessageSendEvent::PaymentFailureNetworkUpdate {
1542                                                                         update,
1543                                                                 }
1544                                                         );
1545                                                 }
1546                                                 self.pending_events.lock().unwrap().push(
1547                                                         events::Event::PaymentFailed {
1548                                                                 payment_hash: payment_hash.clone(),
1549                                                                 rejected_by_dest: !payment_retryable,
1550 #[cfg(test)]
1551                                                                 error_code: onion_error_code
1552                                                         }
1553                                                 );
1554                                         },
1555                                         &HTLCFailReason::Reason {
1556 #[cfg(test)]
1557                                                         ref failure_code,
1558                                                         .. } => {
1559                                                 // we get a fail_malformed_htlc from the first hop
1560                                                 // TODO: We'd like to generate a PaymentFailureNetworkUpdate for temporary
1561                                                 // failures here, but that would be insufficient as Router::get_route
1562                                                 // generally ignores its view of our own channels as we provide them via
1563                                                 // ChannelDetails.
1564                                                 // TODO: For non-temporary failures, we really should be closing the
1565                                                 // channel here as we apparently can't relay through them anyway.
1566                                                 self.pending_events.lock().unwrap().push(
1567                                                         events::Event::PaymentFailed {
1568                                                                 payment_hash: payment_hash.clone(),
1569                                                                 rejected_by_dest: route.hops.len() == 1,
1570 #[cfg(test)]
1571                                                                 error_code: Some(*failure_code),
1572                                                         }
1573                                                 );
1574                                         }
1575                                 }
1576                         },
1577                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
1578                                 let err_packet = match onion_error {
1579                                         HTLCFailReason::Reason { failure_code, data } => {
1580                                                 log_trace!(self, "Failing HTLC with payment_hash {} backwards from us with code {}", log_bytes!(payment_hash.0), failure_code);
1581                                                 let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1582                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1583                                         },
1584                                         HTLCFailReason::ErrorPacket { err } => {
1585                                                 log_trace!(self, "Failing HTLC with payment_hash {} backwards with pre-built ErrorPacket", log_bytes!(payment_hash.0));
1586                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1587                                         }
1588                                 };
1589
1590                                 let channel_state = channel_state_lock.borrow_parts();
1591
1592                                 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1593                                         Some(chan_id) => chan_id.clone(),
1594                                         None => return
1595                                 };
1596
1597                                 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1598                                 match chan.get_update_fail_htlc_and_commit(htlc_id, err_packet) {
1599                                         Ok(Some((msg, commitment_msg, chan_monitor))) => {
1600                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1601                                                         unimplemented!();
1602                                                 }
1603                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1604                                                         node_id: chan.get_their_node_id(),
1605                                                         updates: msgs::CommitmentUpdate {
1606                                                                 update_add_htlcs: Vec::new(),
1607                                                                 update_fulfill_htlcs: Vec::new(),
1608                                                                 update_fail_htlcs: vec![msg],
1609                                                                 update_fail_malformed_htlcs: Vec::new(),
1610                                                                 update_fee: None,
1611                                                                 commitment_signed: commitment_msg,
1612                                                         },
1613                                                 });
1614                                         },
1615                                         Ok(None) => {},
1616                                         Err(_e) => {
1617                                                 //TODO: Do something with e?
1618                                                 return;
1619                                         },
1620                                 }
1621                         },
1622                 }
1623         }
1624
1625         /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1626         /// generating message events for the net layer to claim the payment, if possible. Thus, you
1627         /// should probably kick the net layer to go send messages if this returns true!
1628         ///
1629         /// May panic if called except in response to a PaymentReceived event.
1630         pub fn claim_funds(&self, payment_preimage: PaymentPreimage) -> bool {
1631                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1632
1633                 let _ = self.total_consistency_lock.read().unwrap();
1634
1635                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1636                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&payment_hash);
1637                 if let Some(mut sources) = removed_source {
1638                         for htlc_with_hash in sources.drain(..) {
1639                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1640                                 self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_preimage);
1641                         }
1642                         true
1643                 } else { false }
1644         }
1645         fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_preimage: PaymentPreimage) {
1646                 match source {
1647                         HTLCSource::OutboundRoute { .. } => {
1648                                 mem::drop(channel_state_lock);
1649                                 let mut pending_events = self.pending_events.lock().unwrap();
1650                                 pending_events.push(events::Event::PaymentSent {
1651                                         payment_preimage
1652                                 });
1653                         },
1654                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, .. }) => {
1655                                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1656                                 let channel_state = channel_state_lock.borrow_parts();
1657
1658                                 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1659                                         Some(chan_id) => chan_id.clone(),
1660                                         None => {
1661                                                 // TODO: There is probably a channel manager somewhere that needs to
1662                                                 // learn the preimage as the channel already hit the chain and that's
1663                                                 // why its missing.
1664                                                 return
1665                                         }
1666                                 };
1667
1668                                 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1669                                 match chan.get_update_fulfill_htlc_and_commit(htlc_id, payment_preimage) {
1670                                         Ok((msgs, monitor_option)) => {
1671                                                 if let Some(chan_monitor) = monitor_option {
1672                                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1673                                                                 unimplemented!();// but def dont push the event...
1674                                                         }
1675                                                 }
1676                                                 if let Some((msg, commitment_signed)) = msgs {
1677                                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1678                                                                 node_id: chan.get_their_node_id(),
1679                                                                 updates: msgs::CommitmentUpdate {
1680                                                                         update_add_htlcs: Vec::new(),
1681                                                                         update_fulfill_htlcs: vec![msg],
1682                                                                         update_fail_htlcs: Vec::new(),
1683                                                                         update_fail_malformed_htlcs: Vec::new(),
1684                                                                         update_fee: None,
1685                                                                         commitment_signed,
1686                                                                 }
1687                                                         });
1688                                                 }
1689                                         },
1690                                         Err(_e) => {
1691                                                 // TODO: There is probably a channel manager somewhere that needs to
1692                                                 // learn the preimage as the channel may be about to hit the chain.
1693                                                 //TODO: Do something with e?
1694                                                 return
1695                                         },
1696                                 }
1697                         },
1698                 }
1699         }
1700
1701         /// Gets the node_id held by this ChannelManager
1702         pub fn get_our_node_id(&self) -> PublicKey {
1703                 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
1704         }
1705
1706         /// Used to restore channels to normal operation after a
1707         /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
1708         /// operation.
1709         pub fn test_restore_channel_monitor(&self) {
1710                 let mut close_results = Vec::new();
1711                 let mut htlc_forwards = Vec::new();
1712                 let mut htlc_failures = Vec::new();
1713                 let _ = self.total_consistency_lock.read().unwrap();
1714
1715                 {
1716                         let mut channel_lock = self.channel_state.lock().unwrap();
1717                         let channel_state = channel_lock.borrow_parts();
1718                         let short_to_id = channel_state.short_to_id;
1719                         let pending_msg_events = channel_state.pending_msg_events;
1720                         channel_state.by_id.retain(|_, channel| {
1721                                 if channel.is_awaiting_monitor_update() {
1722                                         let chan_monitor = channel.channel_monitor();
1723                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1724                                                 match e {
1725                                                         ChannelMonitorUpdateErr::PermanentFailure => {
1726                                                                 // TODO: There may be some pending HTLCs that we intended to fail
1727                                                                 // backwards when a monitor update failed. We should make sure
1728                                                                 // knowledge of those gets moved into the appropriate in-memory
1729                                                                 // ChannelMonitor and they get failed backwards once we get
1730                                                                 // on-chain confirmations.
1731                                                                 // Note I think #198 addresses this, so once its merged a test
1732                                                                 // should be written.
1733                                                                 if let Some(short_id) = channel.get_short_channel_id() {
1734                                                                         short_to_id.remove(&short_id);
1735                                                                 }
1736                                                                 close_results.push(channel.force_shutdown());
1737                                                                 if let Ok(update) = self.get_channel_update(&channel) {
1738                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1739                                                                                 msg: update
1740                                                                         });
1741                                                                 }
1742                                                                 false
1743                                                         },
1744                                                         ChannelMonitorUpdateErr::TemporaryFailure => true,
1745                                                 }
1746                                         } else {
1747                                                 let (raa, commitment_update, order, pending_forwards, mut pending_failures) = channel.monitor_updating_restored();
1748                                                 if !pending_forwards.is_empty() {
1749                                                         htlc_forwards.push((channel.get_short_channel_id().expect("We can't have pending forwards before funding confirmation"), pending_forwards));
1750                                                 }
1751                                                 htlc_failures.append(&mut pending_failures);
1752
1753                                                 macro_rules! handle_cs { () => {
1754                                                         if let Some(update) = commitment_update {
1755                                                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1756                                                                         node_id: channel.get_their_node_id(),
1757                                                                         updates: update,
1758                                                                 });
1759                                                         }
1760                                                 } }
1761                                                 macro_rules! handle_raa { () => {
1762                                                         if let Some(revoke_and_ack) = raa {
1763                                                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
1764                                                                         node_id: channel.get_their_node_id(),
1765                                                                         msg: revoke_and_ack,
1766                                                                 });
1767                                                         }
1768                                                 } }
1769                                                 match order {
1770                                                         RAACommitmentOrder::CommitmentFirst => {
1771                                                                 handle_cs!();
1772                                                                 handle_raa!();
1773                                                         },
1774                                                         RAACommitmentOrder::RevokeAndACKFirst => {
1775                                                                 handle_raa!();
1776                                                                 handle_cs!();
1777                                                         },
1778                                                 }
1779                                                 true
1780                                         }
1781                                 } else { true }
1782                         });
1783                 }
1784
1785                 for failure in htlc_failures.drain(..) {
1786                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
1787                 }
1788                 self.forward_htlcs(&mut htlc_forwards[..]);
1789
1790                 for res in close_results.drain(..) {
1791                         self.finish_force_close_channel(res);
1792                 }
1793         }
1794
1795         fn internal_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
1796                 if msg.chain_hash != self.genesis_hash {
1797                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash", msg.temporary_channel_id.clone()));
1798                 }
1799
1800                 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)
1801                         .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
1802                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1803                 let channel_state = channel_state_lock.borrow_parts();
1804                 match channel_state.by_id.entry(channel.channel_id()) {
1805                         hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!", msg.temporary_channel_id.clone())),
1806                         hash_map::Entry::Vacant(entry) => {
1807                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
1808                                         node_id: their_node_id.clone(),
1809                                         msg: channel.get_accept_channel(),
1810                                 });
1811                                 entry.insert(channel);
1812                         }
1813                 }
1814                 Ok(())
1815         }
1816
1817         fn internal_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
1818                 let (value, output_script, user_id) = {
1819                         let mut channel_lock = self.channel_state.lock().unwrap();
1820                         let channel_state = channel_lock.borrow_parts();
1821                         match channel_state.by_id.entry(msg.temporary_channel_id) {
1822                                 hash_map::Entry::Occupied(mut chan) => {
1823                                         if chan.get().get_their_node_id() != *their_node_id {
1824                                                 //TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
1825                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1826                                         }
1827                                         try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration), channel_state, chan);
1828                                         (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
1829                                 },
1830                                 //TODO: same as above
1831                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1832                         }
1833                 };
1834                 let mut pending_events = self.pending_events.lock().unwrap();
1835                 pending_events.push(events::Event::FundingGenerationReady {
1836                         temporary_channel_id: msg.temporary_channel_id,
1837                         channel_value_satoshis: value,
1838                         output_script: output_script,
1839                         user_channel_id: user_id,
1840                 });
1841                 Ok(())
1842         }
1843
1844         fn internal_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
1845                 let ((funding_msg, monitor_update), chan) = {
1846                         let mut channel_lock = self.channel_state.lock().unwrap();
1847                         let channel_state = channel_lock.borrow_parts();
1848                         match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
1849                                 hash_map::Entry::Occupied(mut chan) => {
1850                                         if chan.get().get_their_node_id() != *their_node_id {
1851                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1852                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1853                                         }
1854                                         (try_chan_entry!(self, chan.get_mut().funding_created(msg), channel_state, chan), chan.remove())
1855                                 },
1856                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1857                         }
1858                 };
1859                 // Because we have exclusive ownership of the channel here we can release the channel_state
1860                 // lock before add_update_monitor
1861                 if let Err(_e) = self.monitor.add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) {
1862                         unimplemented!();
1863                 }
1864                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1865                 let channel_state = channel_state_lock.borrow_parts();
1866                 match channel_state.by_id.entry(funding_msg.channel_id) {
1867                         hash_map::Entry::Occupied(_) => {
1868                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id", funding_msg.channel_id))
1869                         },
1870                         hash_map::Entry::Vacant(e) => {
1871                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
1872                                         node_id: their_node_id.clone(),
1873                                         msg: funding_msg,
1874                                 });
1875                                 e.insert(chan);
1876                         }
1877                 }
1878                 Ok(())
1879         }
1880
1881         fn internal_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
1882                 let (funding_txo, user_id) = {
1883                         let mut channel_lock = self.channel_state.lock().unwrap();
1884                         let channel_state = channel_lock.borrow_parts();
1885                         match channel_state.by_id.entry(msg.channel_id) {
1886                                 hash_map::Entry::Occupied(mut chan) => {
1887                                         if chan.get().get_their_node_id() != *their_node_id {
1888                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1889                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1890                                         }
1891                                         let chan_monitor = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
1892                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1893                                                 unimplemented!();
1894                                         }
1895                                         (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())
1896                                 },
1897                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1898                         }
1899                 };
1900                 let mut pending_events = self.pending_events.lock().unwrap();
1901                 pending_events.push(events::Event::FundingBroadcastSafe {
1902                         funding_txo: funding_txo,
1903                         user_channel_id: user_id,
1904                 });
1905                 Ok(())
1906         }
1907
1908         fn internal_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), MsgHandleErrInternal> {
1909                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1910                 let channel_state = channel_state_lock.borrow_parts();
1911                 match channel_state.by_id.entry(msg.channel_id) {
1912                         hash_map::Entry::Occupied(mut chan) => {
1913                                 if chan.get().get_their_node_id() != *their_node_id {
1914                                         //TODO: here and below MsgHandleErrInternal, #153 case
1915                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1916                                 }
1917                                 try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
1918                                 if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
1919                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
1920                                                 node_id: their_node_id.clone(),
1921                                                 msg: announcement_sigs,
1922                                         });
1923                                 }
1924                                 Ok(())
1925                         },
1926                         hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1927                 }
1928         }
1929
1930         fn internal_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
1931                 let (mut dropped_htlcs, chan_option) = {
1932                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1933                         let channel_state = channel_state_lock.borrow_parts();
1934
1935                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1936                                 hash_map::Entry::Occupied(mut chan_entry) => {
1937                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1938                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1939                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1940                                         }
1941                                         let (shutdown, closing_signed, dropped_htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg), channel_state, chan_entry);
1942                                         if let Some(msg) = shutdown {
1943                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
1944                                                         node_id: their_node_id.clone(),
1945                                                         msg,
1946                                                 });
1947                                         }
1948                                         if let Some(msg) = closing_signed {
1949                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1950                                                         node_id: their_node_id.clone(),
1951                                                         msg,
1952                                                 });
1953                                         }
1954                                         if chan_entry.get().is_shutdown() {
1955                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1956                                                         channel_state.short_to_id.remove(&short_id);
1957                                                 }
1958                                                 (dropped_htlcs, Some(chan_entry.remove_entry().1))
1959                                         } else { (dropped_htlcs, None) }
1960                                 },
1961                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1962                         }
1963                 };
1964                 for htlc_source in dropped_htlcs.drain(..) {
1965                         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() });
1966                 }
1967                 if let Some(chan) = chan_option {
1968                         if let Ok(update) = self.get_channel_update(&chan) {
1969                                 let mut channel_state = self.channel_state.lock().unwrap();
1970                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1971                                         msg: update
1972                                 });
1973                         }
1974                 }
1975                 Ok(())
1976         }
1977
1978         fn internal_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
1979                 let (tx, chan_option) = {
1980                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1981                         let channel_state = channel_state_lock.borrow_parts();
1982                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1983                                 hash_map::Entry::Occupied(mut chan_entry) => {
1984                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1985                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1986                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1987                                         }
1988                                         let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg), channel_state, chan_entry);
1989                                         if let Some(msg) = closing_signed {
1990                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1991                                                         node_id: their_node_id.clone(),
1992                                                         msg,
1993                                                 });
1994                                         }
1995                                         if tx.is_some() {
1996                                                 // We're done with this channel, we've got a signed closing transaction and
1997                                                 // will send the closing_signed back to the remote peer upon return. This
1998                                                 // also implies there are no pending HTLCs left on the channel, so we can
1999                                                 // fully delete it from tracking (the channel monitor is still around to
2000                                                 // watch for old state broadcasts)!
2001                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2002                                                         channel_state.short_to_id.remove(&short_id);
2003                                                 }
2004                                                 (tx, Some(chan_entry.remove_entry().1))
2005                                         } else { (tx, None) }
2006                                 },
2007                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2008                         }
2009                 };
2010                 if let Some(broadcast_tx) = tx {
2011                         self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
2012                 }
2013                 if let Some(chan) = chan_option {
2014                         if let Ok(update) = self.get_channel_update(&chan) {
2015                                 let mut channel_state = self.channel_state.lock().unwrap();
2016                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2017                                         msg: update
2018                                 });
2019                         }
2020                 }
2021                 Ok(())
2022         }
2023
2024         fn internal_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
2025                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
2026                 //determine the state of the payment based on our response/if we forward anything/the time
2027                 //we take to respond. We should take care to avoid allowing such an attack.
2028                 //
2029                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
2030                 //us repeatedly garbled in different ways, and compare our error messages, which are
2031                 //encrypted with the same key. Its not immediately obvious how to usefully exploit that,
2032                 //but we should prevent it anyway.
2033
2034                 let (mut pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
2035                 let channel_state = channel_state_lock.borrow_parts();
2036
2037                 match channel_state.by_id.entry(msg.channel_id) {
2038                         hash_map::Entry::Occupied(mut chan) => {
2039                                 if chan.get().get_their_node_id() != *their_node_id {
2040                                         //TODO: here MsgHandleErrInternal, #153 case
2041                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2042                                 }
2043                                 if !chan.get().is_usable() {
2044                                         // If the update_add is completely bogus, the call will Err and we will close,
2045                                         // but if we've sent a shutdown and they haven't acknowledged it yet, we just
2046                                         // want to reject the new HTLC and fail it backwards instead of forwarding.
2047                                         if let PendingHTLCStatus::Forward(PendingForwardHTLCInfo { incoming_shared_secret, .. }) = pending_forward_info {
2048                                                 let chan_update = self.get_channel_update(chan.get());
2049                                                 pending_forward_info = PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
2050                                                         channel_id: msg.channel_id,
2051                                                         htlc_id: msg.htlc_id,
2052                                                         reason: if let Ok(update) = chan_update {
2053                                                                 // TODO: Note that |20 is defined as "channel FROM the processing
2054                                                                 // node has been disabled" (emphasis mine), which seems to imply
2055                                                                 // that we can't return |20 for an inbound channel being disabled.
2056                                                                 // This probably needs a spec update but should definitely be
2057                                                                 // allowed.
2058                                                                 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x1000|20, &{
2059                                                                         let mut res = Vec::with_capacity(8 + 128);
2060                                                                         res.extend_from_slice(&byte_utils::be16_to_array(update.contents.flags));
2061                                                                         res.extend_from_slice(&update.encode_with_len()[..]);
2062                                                                         res
2063                                                                 }[..])
2064                                                         } else {
2065                                                                 // This can only happen if the channel isn't in the fully-funded
2066                                                                 // state yet, implying our counterparty is trying to route payments
2067                                                                 // over the channel back to themselves (cause no one else should
2068                                                                 // know the short_id is a lightning channel yet). We should have no
2069                                                                 // problem just calling this unknown_next_peer
2070                                                                 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x4000|10, &[])
2071                                                         },
2072                                                 }));
2073                                         }
2074                                 }
2075                                 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info), channel_state, chan);
2076                         },
2077                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2078                 }
2079                 Ok(())
2080         }
2081
2082         fn internal_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
2083                 let mut channel_lock = self.channel_state.lock().unwrap();
2084                 let htlc_source = {
2085                         let channel_state = channel_lock.borrow_parts();
2086                         match channel_state.by_id.entry(msg.channel_id) {
2087                                 hash_map::Entry::Occupied(mut chan) => {
2088                                         if chan.get().get_their_node_id() != *their_node_id {
2089                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2090                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2091                                         }
2092                                         try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), channel_state, chan)
2093                                 },
2094                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2095                         }
2096                 };
2097                 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
2098                 Ok(())
2099         }
2100
2101         // Process failure we got back from upstream on a payment we sent. Returns update and a boolean
2102         // indicating that the payment itself failed
2103         fn process_onion_failure(&self, htlc_source: &HTLCSource, mut packet_decrypted: Vec<u8>) -> (Option<msgs::HTLCFailChannelUpdate>, bool, Option<u16>) {
2104                 if let &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } = htlc_source {
2105
2106                         let mut res = None;
2107                         let mut htlc_msat = *first_hop_htlc_msat;
2108                         let mut error_code_ret = None;
2109                         let mut next_route_hop_ix = 0;
2110                         let mut is_from_final_node = false;
2111
2112                         // Handle packed channel/node updates for passing back for the route handler
2113                         Self::construct_onion_keys_callback(&self.secp_ctx, route, session_priv, |shared_secret, _, _, route_hop| {
2114                                 next_route_hop_ix += 1;
2115                                 if res.is_some() { return; }
2116
2117                                 let amt_to_forward = htlc_msat - route_hop.fee_msat;
2118                                 htlc_msat = amt_to_forward;
2119
2120                                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret[..]);
2121
2122                                 let mut decryption_tmp = Vec::with_capacity(packet_decrypted.len());
2123                                 decryption_tmp.resize(packet_decrypted.len(), 0);
2124                                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
2125                                 chacha.process(&packet_decrypted, &mut decryption_tmp[..]);
2126                                 packet_decrypted = decryption_tmp;
2127
2128                                 is_from_final_node = route.hops.last().unwrap().pubkey == route_hop.pubkey;
2129
2130                                 if let Ok(err_packet) = msgs::DecodedOnionErrorPacket::read(&mut Cursor::new(&packet_decrypted)) {
2131                                         let um = ChannelManager::gen_um_from_shared_secret(&shared_secret[..]);
2132                                         let mut hmac = HmacEngine::<Sha256>::new(&um);
2133                                         hmac.input(&err_packet.encode()[32..]);
2134
2135                                         if fixed_time_eq(&Hmac::from_engine(hmac).into_inner(), &err_packet.hmac) {
2136                                                 if let Some(error_code_slice) = err_packet.failuremsg.get(0..2) {
2137                                                         const PERM: u16 = 0x4000;
2138                                                         const NODE: u16 = 0x2000;
2139                                                         const UPDATE: u16 = 0x1000;
2140
2141                                                         let error_code = byte_utils::slice_to_be16(&error_code_slice);
2142                                                         error_code_ret = Some(error_code);
2143
2144                                                         let (debug_field, debug_field_size) = errors::get_onion_debug_field(error_code);
2145
2146                                                         // indicate that payment parameter has failed and no need to
2147                                                         // update Route object
2148                                                         let payment_failed = (match error_code & 0xff {
2149                                                                 15|16|17|18|19 => true,
2150                                                                 _ => false,
2151                                                         } && is_from_final_node) // PERM bit observed below even this error is from the intermediate nodes
2152                                                         || error_code == 21; // Special case error 21 as the Route object is bogus, TODO: Maybe fail the node if the CLTV was reasonable?
2153
2154                                                         let mut fail_channel_update = None;
2155
2156                                                         if error_code & NODE == NODE {
2157                                                                 fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure { node_id: route_hop.pubkey, is_permanent: error_code & PERM == PERM });
2158                                                         }
2159                                                         else if error_code & PERM == PERM {
2160                                                                 fail_channel_update = if payment_failed {None} else {Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
2161                                                                         short_channel_id: route.hops[next_route_hop_ix - if next_route_hop_ix == route.hops.len() { 1 } else { 0 }].short_channel_id,
2162                                                                         is_permanent: true,
2163                                                                 })};
2164                                                         }
2165                                                         else if error_code & UPDATE == UPDATE {
2166                                                                 if let Some(update_len_slice) = err_packet.failuremsg.get(debug_field_size+2..debug_field_size+4) {
2167                                                                         let update_len = byte_utils::slice_to_be16(&update_len_slice) as usize;
2168                                                                         if let Some(update_slice) = err_packet.failuremsg.get(debug_field_size + 4..debug_field_size + 4 + update_len) {
2169                                                                                 if let Ok(chan_update) = msgs::ChannelUpdate::read(&mut Cursor::new(&update_slice)) {
2170                                                                                         // if channel_update should NOT have caused the failure:
2171                                                                                         // MAY treat the channel_update as invalid.
2172                                                                                         let is_chan_update_invalid = match error_code & 0xff {
2173                                                                                                 7 => false,
2174                                                                                                 11 => amt_to_forward > chan_update.contents.htlc_minimum_msat,
2175                                                                                                 12 => {
2176                                                                                                         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) });
2177                                                                                                         new_fee.is_some() && route_hop.fee_msat >= new_fee.unwrap()
2178                                                                                                 }
2179                                                                                                 13 => route_hop.cltv_expiry_delta as u16 >= chan_update.contents.cltv_expiry_delta,
2180                                                                                                 14 => false, // expiry_too_soon; always valid?
2181                                                                                                 20 => chan_update.contents.flags & 2 == 0,
2182                                                                                                 _ => false, // unknown error code; take channel_update as valid
2183                                                                                         };
2184                                                                                         fail_channel_update = if is_chan_update_invalid {
2185                                                                                                 // This probably indicates the node which forwarded
2186                                                                                                 // to the node in question corrupted something.
2187                                                                                                 Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
2188                                                                                                         short_channel_id: route_hop.short_channel_id,
2189                                                                                                         is_permanent: true,
2190                                                                                                 })
2191                                                                                         } else {
2192                                                                                                 Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {
2193                                                                                                         msg: chan_update,
2194                                                                                                 })
2195                                                                                         };
2196                                                                                 }
2197                                                                         }
2198                                                                 }
2199                                                                 if fail_channel_update.is_none() {
2200                                                                         // They provided an UPDATE which was obviously bogus, not worth
2201                                                                         // trying to relay through them anymore.
2202                                                                         fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2203                                                                                 node_id: route_hop.pubkey,
2204                                                                                 is_permanent: true,
2205                                                                         });
2206                                                                 }
2207                                                         } else if !payment_failed {
2208                                                                 // We can't understand their error messages and they failed to
2209                                                                 // forward...they probably can't understand our forwards so its
2210                                                                 // really not worth trying any further.
2211                                                                 fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2212                                                                         node_id: route_hop.pubkey,
2213                                                                         is_permanent: true,
2214                                                                 });
2215                                                         }
2216
2217                                                         // TODO: Here (and a few other places) we assume that BADONION errors
2218                                                         // are always "sourced" from the node previous to the one which failed
2219                                                         // to decode the onion.
2220                                                         res = Some((fail_channel_update, !(error_code & PERM == PERM && is_from_final_node)));
2221
2222                                                         let (description, title) = errors::get_onion_error_description(error_code);
2223                                                         if debug_field_size > 0 && err_packet.failuremsg.len() >= 4 + debug_field_size {
2224                                                                 log_warn!(self, "Onion Error[{}({:#x}) {}({})] {}", title, error_code, debug_field, log_bytes!(&err_packet.failuremsg[4..4+debug_field_size]), description);
2225                                                         }
2226                                                         else {
2227                                                                 log_warn!(self, "Onion Error[{}({:#x})] {}", title, error_code, description);
2228                                                         }
2229                                                 } else {
2230                                                         // Useless packet that we can't use but it passed HMAC, so it
2231                                                         // definitely came from the peer in question
2232                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2233                                                                 node_id: route_hop.pubkey,
2234                                                                 is_permanent: true,
2235                                                         }), !is_from_final_node));
2236                                                 }
2237                                         }
2238                                 }
2239                         }).expect("Route that we sent via spontaneously grew invalid keys in the middle of it?");
2240                         if let Some((channel_update, payment_retryable)) = res {
2241                                 (channel_update, payment_retryable, error_code_ret)
2242                         } else {
2243                                 // only not set either packet unparseable or hmac does not match with any
2244                                 // payment not retryable only when garbage is from the final node
2245                                 (None, !is_from_final_node, None)
2246                         }
2247                 } else { unreachable!(); }
2248         }
2249
2250         fn internal_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
2251                 let mut channel_lock = self.channel_state.lock().unwrap();
2252                 let channel_state = channel_lock.borrow_parts();
2253                 match channel_state.by_id.entry(msg.channel_id) {
2254                         hash_map::Entry::Occupied(mut chan) => {
2255                                 if chan.get().get_their_node_id() != *their_node_id {
2256                                         //TODO: here and below MsgHandleErrInternal, #153 case
2257                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2258                                 }
2259                                 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::ErrorPacket { err: msg.reason.clone() }), channel_state, chan);
2260                         },
2261                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2262                 }
2263                 Ok(())
2264         }
2265
2266         fn internal_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
2267                 let mut channel_lock = self.channel_state.lock().unwrap();
2268                 let channel_state = channel_lock.borrow_parts();
2269                 match channel_state.by_id.entry(msg.channel_id) {
2270                         hash_map::Entry::Occupied(mut chan) => {
2271                                 if chan.get().get_their_node_id() != *their_node_id {
2272                                         //TODO: here and below MsgHandleErrInternal, #153 case
2273                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2274                                 }
2275                                 if (msg.failure_code & 0x8000) == 0 {
2276                                         try_chan_entry!(self, Err(ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set")), channel_state, chan);
2277                                 }
2278                                 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);
2279                                 Ok(())
2280                         },
2281                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2282                 }
2283         }
2284
2285         fn internal_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
2286                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2287                 let channel_state = channel_state_lock.borrow_parts();
2288                 match channel_state.by_id.entry(msg.channel_id) {
2289                         hash_map::Entry::Occupied(mut chan) => {
2290                                 if chan.get().get_their_node_id() != *their_node_id {
2291                                         //TODO: here and below MsgHandleErrInternal, #153 case
2292                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2293                                 }
2294                                 let (revoke_and_ack, commitment_signed, closing_signed, chan_monitor) =
2295                                         try_chan_entry!(self, chan.get_mut().commitment_signed(&msg, &*self.fee_estimator), channel_state, chan);
2296                                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2297                                         return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, commitment_signed.is_some());
2298                                         //TODO: Rebroadcast closing_signed if present on monitor update restoration
2299                                 }
2300                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2301                                         node_id: their_node_id.clone(),
2302                                         msg: revoke_and_ack,
2303                                 });
2304                                 if let Some(msg) = commitment_signed {
2305                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2306                                                 node_id: their_node_id.clone(),
2307                                                 updates: msgs::CommitmentUpdate {
2308                                                         update_add_htlcs: Vec::new(),
2309                                                         update_fulfill_htlcs: Vec::new(),
2310                                                         update_fail_htlcs: Vec::new(),
2311                                                         update_fail_malformed_htlcs: Vec::new(),
2312                                                         update_fee: None,
2313                                                         commitment_signed: msg,
2314                                                 },
2315                                         });
2316                                 }
2317                                 if let Some(msg) = closing_signed {
2318                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2319                                                 node_id: their_node_id.clone(),
2320                                                 msg,
2321                                         });
2322                                 }
2323                                 Ok(())
2324                         },
2325                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2326                 }
2327         }
2328
2329         #[inline]
2330         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64)>)]) {
2331                 for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
2332                         let mut forward_event = None;
2333                         if !pending_forwards.is_empty() {
2334                                 let mut channel_state = self.channel_state.lock().unwrap();
2335                                 if channel_state.forward_htlcs.is_empty() {
2336                                         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));
2337                                         channel_state.next_forward = forward_event.unwrap();
2338                                 }
2339                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2340                                         match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
2341                                                 hash_map::Entry::Occupied(mut entry) => {
2342                                                         entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info });
2343                                                 },
2344                                                 hash_map::Entry::Vacant(entry) => {
2345                                                         entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info }));
2346                                                 }
2347                                         }
2348                                 }
2349                         }
2350                         match forward_event {
2351                                 Some(time) => {
2352                                         let mut pending_events = self.pending_events.lock().unwrap();
2353                                         pending_events.push(events::Event::PendingHTLCsForwardable {
2354                                                 time_forwardable: time
2355                                         });
2356                                 }
2357                                 None => {},
2358                         }
2359                 }
2360         }
2361
2362         fn internal_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
2363                 let (pending_forwards, mut pending_failures, short_channel_id) = {
2364                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2365                         let channel_state = channel_state_lock.borrow_parts();
2366                         match channel_state.by_id.entry(msg.channel_id) {
2367                                 hash_map::Entry::Occupied(mut chan) => {
2368                                         if chan.get().get_their_node_id() != *their_node_id {
2369                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2370                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2371                                         }
2372                                         let (commitment_update, pending_forwards, pending_failures, closing_signed, chan_monitor) =
2373                                                 try_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &*self.fee_estimator), channel_state, chan);
2374                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2375                                                 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, pending_forwards, pending_failures);
2376                                         }
2377                                         if let Some(updates) = commitment_update {
2378                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2379                                                         node_id: their_node_id.clone(),
2380                                                         updates,
2381                                                 });
2382                                         }
2383                                         if let Some(msg) = closing_signed {
2384                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2385                                                         node_id: their_node_id.clone(),
2386                                                         msg,
2387                                                 });
2388                                         }
2389                                         (pending_forwards, pending_failures, chan.get().get_short_channel_id().expect("RAA should only work on a short-id-available channel"))
2390                                 },
2391                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2392                         }
2393                 };
2394                 for failure in pending_failures.drain(..) {
2395                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2396                 }
2397                 self.forward_htlcs(&mut [(short_channel_id, pending_forwards)]);
2398
2399                 Ok(())
2400         }
2401
2402         fn internal_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2403                 let mut channel_lock = self.channel_state.lock().unwrap();
2404                 let channel_state = channel_lock.borrow_parts();
2405                 match channel_state.by_id.entry(msg.channel_id) {
2406                         hash_map::Entry::Occupied(mut chan) => {
2407                                 if chan.get().get_their_node_id() != *their_node_id {
2408                                         //TODO: here and below MsgHandleErrInternal, #153 case
2409                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2410                                 }
2411                                 try_chan_entry!(self, chan.get_mut().update_fee(&*self.fee_estimator, &msg), channel_state, chan);
2412                         },
2413                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2414                 }
2415                 Ok(())
2416         }
2417
2418         fn internal_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2419                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2420                 let channel_state = channel_state_lock.borrow_parts();
2421
2422                 match channel_state.by_id.entry(msg.channel_id) {
2423                         hash_map::Entry::Occupied(mut chan) => {
2424                                 if chan.get().get_their_node_id() != *their_node_id {
2425                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2426                                 }
2427                                 if !chan.get().is_usable() {
2428                                         return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Got an announcement_signatures before we were ready for it", action: Some(msgs::ErrorAction::IgnoreError)}));
2429                                 }
2430
2431                                 let our_node_id = self.get_our_node_id();
2432                                 let (announcement, our_bitcoin_sig) =
2433                                         try_chan_entry!(self, chan.get_mut().get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone()), channel_state, chan);
2434
2435                                 let were_node_one = announcement.node_id_1 == our_node_id;
2436                                 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
2437                                 if self.secp_ctx.verify(&msghash, &msg.node_signature, if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 }).is_err() ||
2438                                                 self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 }).is_err() {
2439                                         try_chan_entry!(self, Err(ChannelError::Close("Bad announcement_signatures node_signature")), channel_state, chan);
2440                                 }
2441
2442                                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2443
2444                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
2445                                         msg: msgs::ChannelAnnouncement {
2446                                                 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
2447                                                 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
2448                                                 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
2449                                                 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
2450                                                 contents: announcement,
2451                                         },
2452                                         update_msg: self.get_channel_update(chan.get()).unwrap(), // can only fail if we're not in a ready state
2453                                 });
2454                         },
2455                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2456                 }
2457                 Ok(())
2458         }
2459
2460         fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
2461                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2462                 let channel_state = channel_state_lock.borrow_parts();
2463
2464                 match channel_state.by_id.entry(msg.channel_id) {
2465                         hash_map::Entry::Occupied(mut chan) => {
2466                                 if chan.get().get_their_node_id() != *their_node_id {
2467                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2468                                 }
2469                                 let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, mut order, shutdown) =
2470                                         try_chan_entry!(self, chan.get_mut().channel_reestablish(msg), channel_state, chan);
2471                                 if let Some(monitor) = channel_monitor {
2472                                         if let Err(e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
2473                                                 // channel_reestablish doesn't guarantee the order it returns is sensical
2474                                                 // for the messages it returns, but if we're setting what messages to
2475                                                 // re-transmit on monitor update success, we need to make sure it is sane.
2476                                                 if revoke_and_ack.is_none() {
2477                                                         order = RAACommitmentOrder::CommitmentFirst;
2478                                                 }
2479                                                 if commitment_update.is_none() {
2480                                                         order = RAACommitmentOrder::RevokeAndACKFirst;
2481                                                 }
2482                                                 return_monitor_err!(self, e, channel_state, chan, order);
2483                                                 //TODO: Resend the funding_locked if needed once we get the monitor running again
2484                                         }
2485                                 }
2486                                 if let Some(msg) = funding_locked {
2487                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2488                                                 node_id: their_node_id.clone(),
2489                                                 msg
2490                                         });
2491                                 }
2492                                 macro_rules! send_raa { () => {
2493                                         if let Some(msg) = revoke_and_ack {
2494                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2495                                                         node_id: their_node_id.clone(),
2496                                                         msg
2497                                                 });
2498                                         }
2499                                 } }
2500                                 macro_rules! send_cu { () => {
2501                                         if let Some(updates) = commitment_update {
2502                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2503                                                         node_id: their_node_id.clone(),
2504                                                         updates
2505                                                 });
2506                                         }
2507                                 } }
2508                                 match order {
2509                                         RAACommitmentOrder::RevokeAndACKFirst => {
2510                                                 send_raa!();
2511                                                 send_cu!();
2512                                         },
2513                                         RAACommitmentOrder::CommitmentFirst => {
2514                                                 send_cu!();
2515                                                 send_raa!();
2516                                         },
2517                                 }
2518                                 if let Some(msg) = shutdown {
2519                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2520                                                 node_id: their_node_id.clone(),
2521                                                 msg,
2522                                         });
2523                                 }
2524                                 Ok(())
2525                         },
2526                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2527                 }
2528         }
2529
2530         /// Begin Update fee process. Allowed only on an outbound channel.
2531         /// If successful, will generate a UpdateHTLCs event, so you should probably poll
2532         /// PeerManager::process_events afterwards.
2533         /// Note: This API is likely to change!
2534         #[doc(hidden)]
2535         pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u64) -> Result<(), APIError> {
2536                 let _ = self.total_consistency_lock.read().unwrap();
2537                 let their_node_id;
2538                 let err: Result<(), _> = loop {
2539                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2540                         let channel_state = channel_state_lock.borrow_parts();
2541
2542                         match channel_state.by_id.entry(channel_id) {
2543                                 hash_map::Entry::Vacant(_) => return Err(APIError::APIMisuseError{err: "Failed to find corresponding channel"}),
2544                                 hash_map::Entry::Occupied(mut chan) => {
2545                                         if !chan.get().is_outbound() {
2546                                                 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel"});
2547                                         }
2548                                         if chan.get().is_awaiting_monitor_update() {
2549                                                 return Err(APIError::MonitorUpdateFailed);
2550                                         }
2551                                         if !chan.get().is_live() {
2552                                                 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected"});
2553                                         }
2554                                         their_node_id = chan.get().get_their_node_id();
2555                                         if let Some((update_fee, commitment_signed, chan_monitor)) =
2556                                                         break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw), channel_state, chan)
2557                                         {
2558                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2559                                                         unimplemented!();
2560                                                 }
2561                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2562                                                         node_id: chan.get().get_their_node_id(),
2563                                                         updates: msgs::CommitmentUpdate {
2564                                                                 update_add_htlcs: Vec::new(),
2565                                                                 update_fulfill_htlcs: Vec::new(),
2566                                                                 update_fail_htlcs: Vec::new(),
2567                                                                 update_fail_malformed_htlcs: Vec::new(),
2568                                                                 update_fee: Some(update_fee),
2569                                                                 commitment_signed,
2570                                                         },
2571                                                 });
2572                                         }
2573                                 },
2574                         }
2575                         return Ok(())
2576                 };
2577
2578                 match handle_error!(self, err, their_node_id) {
2579                         Ok(_) => unreachable!(),
2580                         Err(e) => {
2581                                 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
2582                                 } else {
2583                                         log_error!(self, "Got bad keys: {}!", e.err);
2584                                         let mut channel_state = self.channel_state.lock().unwrap();
2585                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
2586                                                 node_id: their_node_id,
2587                                                 action: e.action,
2588                                         });
2589                                 }
2590                                 Err(APIError::APIMisuseError { err: e.err })
2591                         },
2592                 }
2593         }
2594 }
2595
2596 impl events::MessageSendEventsProvider for ChannelManager {
2597         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
2598                 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2599                 // user to serialize a ChannelManager with pending events in it and lose those events on
2600                 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2601                 {
2602                         //TODO: This behavior should be documented.
2603                         for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2604                                 if let Some(preimage) = htlc_update.payment_preimage {
2605                                         log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2606                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2607                                 } else {
2608                                         log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2609                                         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() });
2610                                 }
2611                         }
2612                 }
2613
2614                 let mut ret = Vec::new();
2615                 let mut channel_state = self.channel_state.lock().unwrap();
2616                 mem::swap(&mut ret, &mut channel_state.pending_msg_events);
2617                 ret
2618         }
2619 }
2620
2621 impl events::EventsProvider for ChannelManager {
2622         fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
2623                 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2624                 // user to serialize a ChannelManager with pending events in it and lose those events on
2625                 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2626                 {
2627                         //TODO: This behavior should be documented.
2628                         for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2629                                 if let Some(preimage) = htlc_update.payment_preimage {
2630                                         log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2631                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2632                                 } else {
2633                                         log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2634                                         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() });
2635                                 }
2636                         }
2637                 }
2638
2639                 let mut ret = Vec::new();
2640                 let mut pending_events = self.pending_events.lock().unwrap();
2641                 mem::swap(&mut ret, &mut *pending_events);
2642                 ret
2643         }
2644 }
2645
2646 impl ChainListener for ChannelManager {
2647         fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
2648                 let header_hash = header.bitcoin_hash();
2649                 log_trace!(self, "Block {} at height {} connected with {} txn matched", header_hash, height, txn_matched.len());
2650                 let _ = self.total_consistency_lock.read().unwrap();
2651                 let mut failed_channels = Vec::new();
2652                 {
2653                         let mut channel_lock = self.channel_state.lock().unwrap();
2654                         let channel_state = channel_lock.borrow_parts();
2655                         let short_to_id = channel_state.short_to_id;
2656                         let pending_msg_events = channel_state.pending_msg_events;
2657                         channel_state.by_id.retain(|_, channel| {
2658                                 let chan_res = channel.block_connected(header, height, txn_matched, indexes_of_txn_matched);
2659                                 if let Ok(Some(funding_locked)) = chan_res {
2660                                         pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2661                                                 node_id: channel.get_their_node_id(),
2662                                                 msg: funding_locked,
2663                                         });
2664                                         if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
2665                                                 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2666                                                         node_id: channel.get_their_node_id(),
2667                                                         msg: announcement_sigs,
2668                                                 });
2669                                         }
2670                                         short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
2671                                 } else if let Err(e) = chan_res {
2672                                         pending_msg_events.push(events::MessageSendEvent::HandleError {
2673                                                 node_id: channel.get_their_node_id(),
2674                                                 action: Some(msgs::ErrorAction::SendErrorMessage { msg: e }),
2675                                         });
2676                                         return false;
2677                                 }
2678                                 if let Some(funding_txo) = channel.get_funding_txo() {
2679                                         for tx in txn_matched {
2680                                                 for inp in tx.input.iter() {
2681                                                         if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
2682                                                                 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()));
2683                                                                 if let Some(short_id) = channel.get_short_channel_id() {
2684                                                                         short_to_id.remove(&short_id);
2685                                                                 }
2686                                                                 // It looks like our counterparty went on-chain. We go ahead and
2687                                                                 // broadcast our latest local state as well here, just in case its
2688                                                                 // some kind of SPV attack, though we expect these to be dropped.
2689                                                                 failed_channels.push(channel.force_shutdown());
2690                                                                 if let Ok(update) = self.get_channel_update(&channel) {
2691                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2692                                                                                 msg: update
2693                                                                         });
2694                                                                 }
2695                                                                 return false;
2696                                                         }
2697                                                 }
2698                                         }
2699                                 }
2700                                 if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height) {
2701                                         if let Some(short_id) = channel.get_short_channel_id() {
2702                                                 short_to_id.remove(&short_id);
2703                                         }
2704                                         failed_channels.push(channel.force_shutdown());
2705                                         // If would_broadcast_at_height() is true, the channel_monitor will broadcast
2706                                         // the latest local tx for us, so we should skip that here (it doesn't really
2707                                         // hurt anything, but does make tests a bit simpler).
2708                                         failed_channels.last_mut().unwrap().0 = Vec::new();
2709                                         if let Ok(update) = self.get_channel_update(&channel) {
2710                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2711                                                         msg: update
2712                                                 });
2713                                         }
2714                                         return false;
2715                                 }
2716                                 true
2717                         });
2718                 }
2719                 for failure in failed_channels.drain(..) {
2720                         self.finish_force_close_channel(failure);
2721                 }
2722                 self.latest_block_height.store(height as usize, Ordering::Release);
2723                 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header_hash;
2724         }
2725
2726         /// We force-close the channel without letting our counterparty participate in the shutdown
2727         fn block_disconnected(&self, header: &BlockHeader) {
2728                 let _ = self.total_consistency_lock.read().unwrap();
2729                 let mut failed_channels = Vec::new();
2730                 {
2731                         let mut channel_lock = self.channel_state.lock().unwrap();
2732                         let channel_state = channel_lock.borrow_parts();
2733                         let short_to_id = channel_state.short_to_id;
2734                         let pending_msg_events = channel_state.pending_msg_events;
2735                         channel_state.by_id.retain(|_,  v| {
2736                                 if v.block_disconnected(header) {
2737                                         if let Some(short_id) = v.get_short_channel_id() {
2738                                                 short_to_id.remove(&short_id);
2739                                         }
2740                                         failed_channels.push(v.force_shutdown());
2741                                         if let Ok(update) = self.get_channel_update(&v) {
2742                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2743                                                         msg: update
2744                                                 });
2745                                         }
2746                                         false
2747                                 } else {
2748                                         true
2749                                 }
2750                         });
2751                 }
2752                 for failure in failed_channels.drain(..) {
2753                         self.finish_force_close_channel(failure);
2754                 }
2755                 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
2756                 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
2757         }
2758 }
2759
2760 impl ChannelMessageHandler for ChannelManager {
2761         //TODO: Handle errors and close channel (or so)
2762         fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), HandleError> {
2763                 let _ = self.total_consistency_lock.read().unwrap();
2764                 handle_error!(self, self.internal_open_channel(their_node_id, msg), their_node_id)
2765         }
2766
2767         fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), HandleError> {
2768                 let _ = self.total_consistency_lock.read().unwrap();
2769                 handle_error!(self, self.internal_accept_channel(their_node_id, msg), their_node_id)
2770         }
2771
2772         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), HandleError> {
2773                 let _ = self.total_consistency_lock.read().unwrap();
2774                 handle_error!(self, self.internal_funding_created(their_node_id, msg), their_node_id)
2775         }
2776
2777         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), HandleError> {
2778                 let _ = self.total_consistency_lock.read().unwrap();
2779                 handle_error!(self, self.internal_funding_signed(their_node_id, msg), their_node_id)
2780         }
2781
2782         fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), HandleError> {
2783                 let _ = self.total_consistency_lock.read().unwrap();
2784                 handle_error!(self, self.internal_funding_locked(their_node_id, msg), their_node_id)
2785         }
2786
2787         fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), HandleError> {
2788                 let _ = self.total_consistency_lock.read().unwrap();
2789                 handle_error!(self, self.internal_shutdown(their_node_id, msg), their_node_id)
2790         }
2791
2792         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), HandleError> {
2793                 let _ = self.total_consistency_lock.read().unwrap();
2794                 handle_error!(self, self.internal_closing_signed(their_node_id, msg), their_node_id)
2795         }
2796
2797         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), msgs::HandleError> {
2798                 let _ = self.total_consistency_lock.read().unwrap();
2799                 handle_error!(self, self.internal_update_add_htlc(their_node_id, msg), their_node_id)
2800         }
2801
2802         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), HandleError> {
2803                 let _ = self.total_consistency_lock.read().unwrap();
2804                 handle_error!(self, self.internal_update_fulfill_htlc(their_node_id, msg), their_node_id)
2805         }
2806
2807         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), HandleError> {
2808                 let _ = self.total_consistency_lock.read().unwrap();
2809                 handle_error!(self, self.internal_update_fail_htlc(their_node_id, msg), their_node_id)
2810         }
2811
2812         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), HandleError> {
2813                 let _ = self.total_consistency_lock.read().unwrap();
2814                 handle_error!(self, self.internal_update_fail_malformed_htlc(their_node_id, msg), their_node_id)
2815         }
2816
2817         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), HandleError> {
2818                 let _ = self.total_consistency_lock.read().unwrap();
2819                 handle_error!(self, self.internal_commitment_signed(their_node_id, msg), their_node_id)
2820         }
2821
2822         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), HandleError> {
2823                 let _ = self.total_consistency_lock.read().unwrap();
2824                 handle_error!(self, self.internal_revoke_and_ack(their_node_id, msg), their_node_id)
2825         }
2826
2827         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), HandleError> {
2828                 let _ = self.total_consistency_lock.read().unwrap();
2829                 handle_error!(self, self.internal_update_fee(their_node_id, msg), their_node_id)
2830         }
2831
2832         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), HandleError> {
2833                 let _ = self.total_consistency_lock.read().unwrap();
2834                 handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
2835         }
2836
2837         fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), HandleError> {
2838                 let _ = self.total_consistency_lock.read().unwrap();
2839                 handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), their_node_id)
2840         }
2841
2842         fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
2843                 let _ = self.total_consistency_lock.read().unwrap();
2844                 let mut failed_channels = Vec::new();
2845                 let mut failed_payments = Vec::new();
2846                 {
2847                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2848                         let channel_state = channel_state_lock.borrow_parts();
2849                         let short_to_id = channel_state.short_to_id;
2850                         let pending_msg_events = channel_state.pending_msg_events;
2851                         if no_connection_possible {
2852                                 log_debug!(self, "Failing all channels with {} due to no_connection_possible", log_pubkey!(their_node_id));
2853                                 channel_state.by_id.retain(|_, chan| {
2854                                         if chan.get_their_node_id() == *their_node_id {
2855                                                 if let Some(short_id) = chan.get_short_channel_id() {
2856                                                         short_to_id.remove(&short_id);
2857                                                 }
2858                                                 failed_channels.push(chan.force_shutdown());
2859                                                 if let Ok(update) = self.get_channel_update(&chan) {
2860                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2861                                                                 msg: update
2862                                                         });
2863                                                 }
2864                                                 false
2865                                         } else {
2866                                                 true
2867                                         }
2868                                 });
2869                         } else {
2870                                 log_debug!(self, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(their_node_id));
2871                                 channel_state.by_id.retain(|_, chan| {
2872                                         if chan.get_their_node_id() == *their_node_id {
2873                                                 //TODO: mark channel disabled (and maybe announce such after a timeout).
2874                                                 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused();
2875                                                 if !failed_adds.is_empty() {
2876                                                         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
2877                                                         failed_payments.push((chan_update, failed_adds));
2878                                                 }
2879                                                 if chan.is_shutdown() {
2880                                                         if let Some(short_id) = chan.get_short_channel_id() {
2881                                                                 short_to_id.remove(&short_id);
2882                                                         }
2883                                                         return false;
2884                                                 }
2885                                         }
2886                                         true
2887                                 })
2888                         }
2889                 }
2890                 for failure in failed_channels.drain(..) {
2891                         self.finish_force_close_channel(failure);
2892                 }
2893                 for (chan_update, mut htlc_sources) in failed_payments {
2894                         for (htlc_source, payment_hash) in htlc_sources.drain(..) {
2895                                 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
2896                         }
2897                 }
2898         }
2899
2900         fn peer_connected(&self, their_node_id: &PublicKey) {
2901                 log_debug!(self, "Generating channel_reestablish events for {}", log_pubkey!(their_node_id));
2902
2903                 let _ = self.total_consistency_lock.read().unwrap();
2904                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2905                 let channel_state = channel_state_lock.borrow_parts();
2906                 let pending_msg_events = channel_state.pending_msg_events;
2907                 channel_state.by_id.retain(|_, chan| {
2908                         if chan.get_their_node_id() == *their_node_id {
2909                                 if !chan.have_received_message() {
2910                                         // If we created this (outbound) channel while we were disconnected from the
2911                                         // peer we probably failed to send the open_channel message, which is now
2912                                         // lost. We can't have had anything pending related to this channel, so we just
2913                                         // drop it.
2914                                         false
2915                                 } else {
2916                                         pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
2917                                                 node_id: chan.get_their_node_id(),
2918                                                 msg: chan.get_channel_reestablish(),
2919                                         });
2920                                         true
2921                                 }
2922                         } else { true }
2923                 });
2924                 //TODO: Also re-broadcast announcement_signatures
2925         }
2926
2927         fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
2928                 let _ = self.total_consistency_lock.read().unwrap();
2929
2930                 if msg.channel_id == [0; 32] {
2931                         for chan in self.list_channels() {
2932                                 if chan.remote_network_id == *their_node_id {
2933                                         self.force_close_channel(&chan.channel_id);
2934                                 }
2935                         }
2936                 } else {
2937                         self.force_close_channel(&msg.channel_id);
2938                 }
2939         }
2940 }
2941
2942 const SERIALIZATION_VERSION: u8 = 1;
2943 const MIN_SERIALIZATION_VERSION: u8 = 1;
2944
2945 impl Writeable for PendingForwardHTLCInfo {
2946         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2947                 if let &Some(ref onion) = &self.onion_packet {
2948                         1u8.write(writer)?;
2949                         onion.write(writer)?;
2950                 } else {
2951                         0u8.write(writer)?;
2952                 }
2953                 self.incoming_shared_secret.write(writer)?;
2954                 self.payment_hash.write(writer)?;
2955                 self.short_channel_id.write(writer)?;
2956                 self.amt_to_forward.write(writer)?;
2957                 self.outgoing_cltv_value.write(writer)?;
2958                 Ok(())
2959         }
2960 }
2961
2962 impl<R: ::std::io::Read> Readable<R> for PendingForwardHTLCInfo {
2963         fn read(reader: &mut R) -> Result<PendingForwardHTLCInfo, DecodeError> {
2964                 let onion_packet = match <u8 as Readable<R>>::read(reader)? {
2965                         0 => None,
2966                         1 => Some(msgs::OnionPacket::read(reader)?),
2967                         _ => return Err(DecodeError::InvalidValue),
2968                 };
2969                 Ok(PendingForwardHTLCInfo {
2970                         onion_packet,
2971                         incoming_shared_secret: Readable::read(reader)?,
2972                         payment_hash: Readable::read(reader)?,
2973                         short_channel_id: Readable::read(reader)?,
2974                         amt_to_forward: Readable::read(reader)?,
2975                         outgoing_cltv_value: Readable::read(reader)?,
2976                 })
2977         }
2978 }
2979
2980 impl Writeable for HTLCFailureMsg {
2981         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2982                 match self {
2983                         &HTLCFailureMsg::Relay(ref fail_msg) => {
2984                                 0u8.write(writer)?;
2985                                 fail_msg.write(writer)?;
2986                         },
2987                         &HTLCFailureMsg::Malformed(ref fail_msg) => {
2988                                 1u8.write(writer)?;
2989                                 fail_msg.write(writer)?;
2990                         }
2991                 }
2992                 Ok(())
2993         }
2994 }
2995
2996 impl<R: ::std::io::Read> Readable<R> for HTLCFailureMsg {
2997         fn read(reader: &mut R) -> Result<HTLCFailureMsg, DecodeError> {
2998                 match <u8 as Readable<R>>::read(reader)? {
2999                         0 => Ok(HTLCFailureMsg::Relay(Readable::read(reader)?)),
3000                         1 => Ok(HTLCFailureMsg::Malformed(Readable::read(reader)?)),
3001                         _ => Err(DecodeError::InvalidValue),
3002                 }
3003         }
3004 }
3005
3006 impl Writeable for PendingHTLCStatus {
3007         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3008                 match self {
3009                         &PendingHTLCStatus::Forward(ref forward_info) => {
3010                                 0u8.write(writer)?;
3011                                 forward_info.write(writer)?;
3012                         },
3013                         &PendingHTLCStatus::Fail(ref fail_msg) => {
3014                                 1u8.write(writer)?;
3015                                 fail_msg.write(writer)?;
3016                         }
3017                 }
3018                 Ok(())
3019         }
3020 }
3021
3022 impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
3023         fn read(reader: &mut R) -> Result<PendingHTLCStatus, DecodeError> {
3024                 match <u8 as Readable<R>>::read(reader)? {
3025                         0 => Ok(PendingHTLCStatus::Forward(Readable::read(reader)?)),
3026                         1 => Ok(PendingHTLCStatus::Fail(Readable::read(reader)?)),
3027                         _ => Err(DecodeError::InvalidValue),
3028                 }
3029         }
3030 }
3031
3032 impl_writeable!(HTLCPreviousHopData, 0, {
3033         short_channel_id,
3034         htlc_id,
3035         incoming_packet_shared_secret
3036 });
3037
3038 impl Writeable for HTLCSource {
3039         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3040                 match self {
3041                         &HTLCSource::PreviousHopData(ref hop_data) => {
3042                                 0u8.write(writer)?;
3043                                 hop_data.write(writer)?;
3044                         },
3045                         &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } => {
3046                                 1u8.write(writer)?;
3047                                 route.write(writer)?;
3048                                 session_priv.write(writer)?;
3049                                 first_hop_htlc_msat.write(writer)?;
3050                         }
3051                 }
3052                 Ok(())
3053         }
3054 }
3055
3056 impl<R: ::std::io::Read> Readable<R> for HTLCSource {
3057         fn read(reader: &mut R) -> Result<HTLCSource, DecodeError> {
3058                 match <u8 as Readable<R>>::read(reader)? {
3059                         0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
3060                         1 => Ok(HTLCSource::OutboundRoute {
3061                                 route: Readable::read(reader)?,
3062                                 session_priv: Readable::read(reader)?,
3063                                 first_hop_htlc_msat: Readable::read(reader)?,
3064                         }),
3065                         _ => Err(DecodeError::InvalidValue),
3066                 }
3067         }
3068 }
3069
3070 impl Writeable for HTLCFailReason {
3071         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3072                 match self {
3073                         &HTLCFailReason::ErrorPacket { ref err } => {
3074                                 0u8.write(writer)?;
3075                                 err.write(writer)?;
3076                         },
3077                         &HTLCFailReason::Reason { ref failure_code, ref data } => {
3078                                 1u8.write(writer)?;
3079                                 failure_code.write(writer)?;
3080                                 data.write(writer)?;
3081                         }
3082                 }
3083                 Ok(())
3084         }
3085 }
3086
3087 impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
3088         fn read(reader: &mut R) -> Result<HTLCFailReason, DecodeError> {
3089                 match <u8 as Readable<R>>::read(reader)? {
3090                         0 => Ok(HTLCFailReason::ErrorPacket { err: Readable::read(reader)? }),
3091                         1 => Ok(HTLCFailReason::Reason {
3092                                 failure_code: Readable::read(reader)?,
3093                                 data: Readable::read(reader)?,
3094                         }),
3095                         _ => Err(DecodeError::InvalidValue),
3096                 }
3097         }
3098 }
3099
3100 impl_writeable!(HTLCForwardInfo, 0, {
3101         prev_short_channel_id,
3102         prev_htlc_id,
3103         forward_info
3104 });
3105
3106 impl Writeable for ChannelManager {
3107         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3108                 let _ = self.total_consistency_lock.write().unwrap();
3109
3110                 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
3111                 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
3112
3113                 self.genesis_hash.write(writer)?;
3114                 (self.latest_block_height.load(Ordering::Acquire) as u32).write(writer)?;
3115                 self.last_block_hash.lock().unwrap().write(writer)?;
3116
3117                 let channel_state = self.channel_state.lock().unwrap();
3118                 let mut unfunded_channels = 0;
3119                 for (_, channel) in channel_state.by_id.iter() {
3120                         if !channel.is_funding_initiated() {
3121                                 unfunded_channels += 1;
3122                         }
3123                 }
3124                 ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
3125                 for (_, channel) in channel_state.by_id.iter() {
3126                         if channel.is_funding_initiated() {
3127                                 channel.write(writer)?;
3128                         }
3129                 }
3130
3131                 (channel_state.forward_htlcs.len() as u64).write(writer)?;
3132                 for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
3133                         short_channel_id.write(writer)?;
3134                         (pending_forwards.len() as u64).write(writer)?;
3135                         for forward in pending_forwards {
3136                                 forward.write(writer)?;
3137                         }
3138                 }
3139
3140                 (channel_state.claimable_htlcs.len() as u64).write(writer)?;
3141                 for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
3142                         payment_hash.write(writer)?;
3143                         (previous_hops.len() as u64).write(writer)?;
3144                         for previous_hop in previous_hops {
3145                                 previous_hop.write(writer)?;
3146                         }
3147                 }
3148
3149                 Ok(())
3150         }
3151 }
3152
3153 /// Arguments for the creation of a ChannelManager that are not deserialized.
3154 ///
3155 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
3156 /// is:
3157 /// 1) Deserialize all stored ChannelMonitors.
3158 /// 2) Deserialize the ChannelManager by filling in this struct and calling <(Sha256dHash,
3159 ///    ChannelManager)>::read(reader, args).
3160 ///    This may result in closing some Channels if the ChannelMonitor is newer than the stored
3161 ///    ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
3162 /// 3) Register all relevant ChannelMonitor outpoints with your chain watch mechanism using
3163 ///    ChannelMonitor::get_monitored_outpoints and ChannelMonitor::get_funding_txo().
3164 /// 4) Reconnect blocks on your ChannelMonitors.
3165 /// 5) Move the ChannelMonitors into your local ManyChannelMonitor.
3166 /// 6) Disconnect/connect blocks on the ChannelManager.
3167 /// 7) Register the new ChannelManager with your ChainWatchInterface (this does not happen
3168 ///    automatically as it does in ChannelManager::new()).
3169 pub struct ChannelManagerReadArgs<'a> {
3170         /// The keys provider which will give us relevant keys. Some keys will be loaded during
3171         /// deserialization.
3172         pub keys_manager: Arc<KeysInterface>,
3173
3174         /// The fee_estimator for use in the ChannelManager in the future.
3175         ///
3176         /// No calls to the FeeEstimator will be made during deserialization.
3177         pub fee_estimator: Arc<FeeEstimator>,
3178         /// The ManyChannelMonitor for use in the ChannelManager in the future.
3179         ///
3180         /// No calls to the ManyChannelMonitor will be made during deserialization. It is assumed that
3181         /// you have deserialized ChannelMonitors separately and will add them to your
3182         /// ManyChannelMonitor after deserializing this ChannelManager.
3183         pub monitor: Arc<ManyChannelMonitor>,
3184         /// The ChainWatchInterface for use in the ChannelManager in the future.
3185         ///
3186         /// No calls to the ChainWatchInterface will be made during deserialization.
3187         pub chain_monitor: Arc<ChainWatchInterface>,
3188         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
3189         /// used to broadcast the latest local commitment transactions of channels which must be
3190         /// force-closed during deserialization.
3191         pub tx_broadcaster: Arc<BroadcasterInterface>,
3192         /// The Logger for use in the ChannelManager and which may be used to log information during
3193         /// deserialization.
3194         pub logger: Arc<Logger>,
3195         /// Default settings used for new channels. Any existing channels will continue to use the
3196         /// runtime settings which were stored when the ChannelManager was serialized.
3197         pub default_config: UserConfig,
3198
3199         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
3200         /// value.get_funding_txo() should be the key).
3201         ///
3202         /// If a monitor is inconsistent with the channel state during deserialization the channel will
3203         /// be force-closed using the data in the channelmonitor and the Channel will be dropped. This
3204         /// is true for missing channels as well. If there is a monitor missing for which we find
3205         /// channel data Err(DecodeError::InvalidValue) will be returned.
3206         ///
3207         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
3208         /// this struct.
3209         pub channel_monitors: &'a HashMap<OutPoint, &'a ChannelMonitor>,
3210 }
3211
3212 impl<'a, R : ::std::io::Read> ReadableArgs<R, ChannelManagerReadArgs<'a>> for (Sha256dHash, ChannelManager) {
3213         fn read(reader: &mut R, args: ChannelManagerReadArgs<'a>) -> Result<Self, DecodeError> {
3214                 let _ver: u8 = Readable::read(reader)?;
3215                 let min_ver: u8 = Readable::read(reader)?;
3216                 if min_ver > SERIALIZATION_VERSION {
3217                         return Err(DecodeError::UnknownVersion);
3218                 }
3219
3220                 let genesis_hash: Sha256dHash = Readable::read(reader)?;
3221                 let latest_block_height: u32 = Readable::read(reader)?;
3222                 let last_block_hash: Sha256dHash = Readable::read(reader)?;
3223
3224                 let mut closed_channels = Vec::new();
3225
3226                 let channel_count: u64 = Readable::read(reader)?;
3227                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
3228                 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3229                 let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3230                 for _ in 0..channel_count {
3231                         let mut channel: Channel = ReadableArgs::read(reader, args.logger.clone())?;
3232                         if channel.last_block_connected != last_block_hash {
3233                                 return Err(DecodeError::InvalidValue);
3234                         }
3235
3236                         let funding_txo = channel.channel_monitor().get_funding_txo().ok_or(DecodeError::InvalidValue)?;
3237                         funding_txo_set.insert(funding_txo.clone());
3238                         if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
3239                                 if channel.get_cur_local_commitment_transaction_number() != monitor.get_cur_local_commitment_number() ||
3240                                                 channel.get_revoked_remote_commitment_transaction_number() != monitor.get_min_seen_secret() ||
3241                                                 channel.get_cur_remote_commitment_transaction_number() != monitor.get_cur_remote_commitment_number() {
3242                                         let mut force_close_res = channel.force_shutdown();
3243                                         force_close_res.0 = monitor.get_latest_local_commitment_txn();
3244                                         closed_channels.push(force_close_res);
3245                                 } else {
3246                                         if let Some(short_channel_id) = channel.get_short_channel_id() {
3247                                                 short_to_id.insert(short_channel_id, channel.channel_id());
3248                                         }
3249                                         by_id.insert(channel.channel_id(), channel);
3250                                 }
3251                         } else {
3252                                 return Err(DecodeError::InvalidValue);
3253                         }
3254                 }
3255
3256                 for (ref funding_txo, ref monitor) in args.channel_monitors.iter() {
3257                         if !funding_txo_set.contains(funding_txo) {
3258                                 closed_channels.push((monitor.get_latest_local_commitment_txn(), Vec::new()));
3259                         }
3260                 }
3261
3262                 let forward_htlcs_count: u64 = Readable::read(reader)?;
3263                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
3264                 for _ in 0..forward_htlcs_count {
3265                         let short_channel_id = Readable::read(reader)?;
3266                         let pending_forwards_count: u64 = Readable::read(reader)?;
3267                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, 128));
3268                         for _ in 0..pending_forwards_count {
3269                                 pending_forwards.push(Readable::read(reader)?);
3270                         }
3271                         forward_htlcs.insert(short_channel_id, pending_forwards);
3272                 }
3273
3274                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
3275                 let mut claimable_htlcs = HashMap::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
3276                 for _ in 0..claimable_htlcs_count {
3277                         let payment_hash = Readable::read(reader)?;
3278                         let previous_hops_len: u64 = Readable::read(reader)?;
3279                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, 2));
3280                         for _ in 0..previous_hops_len {
3281                                 previous_hops.push(Readable::read(reader)?);
3282                         }
3283                         claimable_htlcs.insert(payment_hash, previous_hops);
3284                 }
3285
3286                 let channel_manager = ChannelManager {
3287                         genesis_hash,
3288                         fee_estimator: args.fee_estimator,
3289                         monitor: args.monitor,
3290                         chain_monitor: args.chain_monitor,
3291                         tx_broadcaster: args.tx_broadcaster,
3292
3293                         latest_block_height: AtomicUsize::new(latest_block_height as usize),
3294                         last_block_hash: Mutex::new(last_block_hash),
3295                         secp_ctx: Secp256k1::new(),
3296
3297                         channel_state: Mutex::new(ChannelHolder {
3298                                 by_id,
3299                                 short_to_id,
3300                                 next_forward: Instant::now(),
3301                                 forward_htlcs,
3302                                 claimable_htlcs,
3303                                 pending_msg_events: Vec::new(),
3304                         }),
3305                         our_network_key: args.keys_manager.get_node_secret(),
3306
3307                         pending_events: Mutex::new(Vec::new()),
3308                         total_consistency_lock: RwLock::new(()),
3309                         keys_manager: args.keys_manager,
3310                         logger: args.logger,
3311                         default_configuration: args.default_config,
3312                 };
3313
3314                 for close_res in closed_channels.drain(..) {
3315                         channel_manager.finish_force_close_channel(close_res);
3316                         //TODO: Broadcast channel update for closed channels, but only after we've made a
3317                         //connection or two.
3318                 }
3319
3320                 Ok((last_block_hash.clone(), channel_manager))
3321         }
3322 }
3323
3324 #[cfg(test)]
3325 mod tests {
3326         use chain::chaininterface;
3327         use chain::transaction::OutPoint;
3328         use chain::chaininterface::{ChainListener, ChainWatchInterface};
3329         use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor};
3330         use chain::keysinterface;
3331         use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
3332         use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,OnionKeys,RAACommitmentOrder, PaymentPreimage, PaymentHash};
3333         use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, ManyChannelMonitor};
3334         use ln::channel::{ACCEPTED_HTLC_SCRIPT_WEIGHT, OFFERED_HTLC_SCRIPT_WEIGHT};
3335         use ln::router::{Route, RouteHop, Router};
3336         use ln::msgs;
3337         use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate};
3338         use util::test_utils;
3339         use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
3340         use util::errors::APIError;
3341         use util::logger::Logger;
3342         use util::ser::{Writeable, Writer, ReadableArgs};
3343         use util::config::UserConfig;
3344
3345         use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
3346         use bitcoin::util::bip143;
3347         use bitcoin::util::address::Address;
3348         use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
3349         use bitcoin::blockdata::block::{Block, BlockHeader};
3350         use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType};
3351         use bitcoin::blockdata::script::{Builder, Script};
3352         use bitcoin::blockdata::opcodes;
3353         use bitcoin::blockdata::constants::genesis_block;
3354         use bitcoin::network::constants::Network;
3355
3356         use bitcoin_hashes::sha256::Hash as Sha256;
3357         use bitcoin_hashes::Hash;
3358
3359         use hex;
3360
3361         use secp256k1::{Secp256k1, Message};
3362         use secp256k1::key::{PublicKey,SecretKey};
3363
3364         use rand::{thread_rng,Rng};
3365
3366         use std::cell::RefCell;
3367         use std::collections::{BTreeSet, HashMap, HashSet};
3368         use std::default::Default;
3369         use std::rc::Rc;
3370         use std::sync::{Arc, Mutex};
3371         use std::sync::atomic::Ordering;
3372         use std::time::Instant;
3373         use std::mem;
3374
3375         fn build_test_onion_keys() -> Vec<OnionKeys> {
3376                 // Keys from BOLT 4, used in both test vector tests
3377                 let secp_ctx = Secp256k1::new();
3378
3379                 let route = Route {
3380                         hops: vec!(
3381                                         RouteHop {
3382                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
3383                                                 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
3384                                         },
3385                                         RouteHop {
3386                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
3387                                                 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
3388                                         },
3389                                         RouteHop {
3390                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
3391                                                 short_channel_id: 0, fee_msat: 0, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
3392                                         },
3393                                         RouteHop {
3394                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..]).unwrap(),
3395                                                 short_channel_id: 0, fee_msat: 0, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
3396                                         },
3397                                         RouteHop {
3398                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145").unwrap()[..]).unwrap(),
3399                                                 short_channel_id: 0, fee_msat: 0, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
3400                                         },
3401                         ),
3402                 };
3403
3404                 let session_priv = SecretKey::from_slice(&secp_ctx, &hex::decode("4141414141414141414141414141414141414141414141414141414141414141").unwrap()[..]).unwrap();
3405
3406                 let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
3407                 assert_eq!(onion_keys.len(), route.hops.len());
3408                 onion_keys
3409         }
3410
3411         #[test]
3412         fn onion_vectors() {
3413                 // Packet creation test vectors from BOLT 4
3414                 let onion_keys = build_test_onion_keys();
3415
3416                 assert_eq!(onion_keys[0].shared_secret[..], hex::decode("53eb63ea8a3fec3b3cd433b85cd62a4b145e1dda09391b348c4e1cd36a03ea66").unwrap()[..]);
3417                 assert_eq!(onion_keys[0].blinding_factor[..], hex::decode("2ec2e5da605776054187180343287683aa6a51b4b1c04d6dd49c45d8cffb3c36").unwrap()[..]);
3418                 assert_eq!(onion_keys[0].ephemeral_pubkey.serialize()[..], hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]);
3419                 assert_eq!(onion_keys[0].rho, hex::decode("ce496ec94def95aadd4bec15cdb41a740c9f2b62347c4917325fcc6fb0453986").unwrap()[..]);
3420                 assert_eq!(onion_keys[0].mu, hex::decode("b57061dc6d0a2b9f261ac410c8b26d64ac5506cbba30267a649c28c179400eba").unwrap()[..]);
3421
3422                 assert_eq!(onion_keys[1].shared_secret[..], hex::decode("a6519e98832a0b179f62123b3567c106db99ee37bef036e783263602f3488fae").unwrap()[..]);
3423                 assert_eq!(onion_keys[1].blinding_factor[..], hex::decode("bf66c28bc22e598cfd574a1931a2bafbca09163df2261e6d0056b2610dab938f").unwrap()[..]);
3424                 assert_eq!(onion_keys[1].ephemeral_pubkey.serialize()[..], hex::decode("028f9438bfbf7feac2e108d677e3a82da596be706cc1cf342b75c7b7e22bf4e6e2").unwrap()[..]);
3425                 assert_eq!(onion_keys[1].rho, hex::decode("450ffcabc6449094918ebe13d4f03e433d20a3d28a768203337bc40b6e4b2c59").unwrap()[..]);
3426                 assert_eq!(onion_keys[1].mu, hex::decode("05ed2b4a3fb023c2ff5dd6ed4b9b6ea7383f5cfe9d59c11d121ec2c81ca2eea9").unwrap()[..]);
3427
3428                 assert_eq!(onion_keys[2].shared_secret[..], hex::decode("3a6b412548762f0dbccce5c7ae7bb8147d1caf9b5471c34120b30bc9c04891cc").unwrap()[..]);
3429                 assert_eq!(onion_keys[2].blinding_factor[..], hex::decode("a1f2dadd184eb1627049673f18c6325814384facdee5bfd935d9cb031a1698a5").unwrap()[..]);
3430                 assert_eq!(onion_keys[2].ephemeral_pubkey.serialize()[..], hex::decode("03bfd8225241ea71cd0843db7709f4c222f62ff2d4516fd38b39914ab6b83e0da0").unwrap()[..]);
3431                 assert_eq!(onion_keys[2].rho, hex::decode("11bf5c4f960239cb37833936aa3d02cea82c0f39fd35f566109c41f9eac8deea").unwrap()[..]);
3432                 assert_eq!(onion_keys[2].mu, hex::decode("caafe2820fa00eb2eeb78695ae452eba38f5a53ed6d53518c5c6edf76f3f5b78").unwrap()[..]);
3433
3434                 assert_eq!(onion_keys[3].shared_secret[..], hex::decode("21e13c2d7cfe7e18836df50872466117a295783ab8aab0e7ecc8c725503ad02d").unwrap()[..]);
3435                 assert_eq!(onion_keys[3].blinding_factor[..], hex::decode("7cfe0b699f35525029ae0fa437c69d0f20f7ed4e3916133f9cacbb13c82ff262").unwrap()[..]);
3436                 assert_eq!(onion_keys[3].ephemeral_pubkey.serialize()[..], hex::decode("031dde6926381289671300239ea8e57ffaf9bebd05b9a5b95beaf07af05cd43595").unwrap()[..]);
3437                 assert_eq!(onion_keys[3].rho, hex::decode("cbe784ab745c13ff5cffc2fbe3e84424aa0fd669b8ead4ee562901a4a4e89e9e").unwrap()[..]);
3438                 assert_eq!(onion_keys[3].mu, hex::decode("5052aa1b3d9f0655a0932e50d42f0c9ba0705142c25d225515c45f47c0036ee9").unwrap()[..]);
3439
3440                 assert_eq!(onion_keys[4].shared_secret[..], hex::decode("b5756b9b542727dbafc6765a49488b023a725d631af688fc031217e90770c328").unwrap()[..]);
3441                 assert_eq!(onion_keys[4].blinding_factor[..], hex::decode("c96e00dddaf57e7edcd4fb5954be5b65b09f17cb6d20651b4e90315be5779205").unwrap()[..]);
3442                 assert_eq!(onion_keys[4].ephemeral_pubkey.serialize()[..], hex::decode("03a214ebd875aab6ddfd77f22c5e7311d7f77f17a169e599f157bbcdae8bf071f4").unwrap()[..]);
3443                 assert_eq!(onion_keys[4].rho, hex::decode("034e18b8cc718e8af6339106e706c52d8df89e2b1f7e9142d996acf88df8799b").unwrap()[..]);
3444                 assert_eq!(onion_keys[4].mu, hex::decode("8e45e5c61c2b24cb6382444db6698727afb063adecd72aada233d4bf273d975a").unwrap()[..]);
3445
3446                 // Test vectors below are flat-out wrong: they claim to set outgoing_cltv_value to non-0 :/
3447                 let payloads = vec!(
3448                         msgs::OnionHopData {
3449                                 realm: 0,
3450                                 data: msgs::OnionRealm0HopData {
3451                                         short_channel_id: 0,
3452                                         amt_to_forward: 0,
3453                                         outgoing_cltv_value: 0,
3454                                 },
3455                                 hmac: [0; 32],
3456                         },
3457                         msgs::OnionHopData {
3458                                 realm: 0,
3459                                 data: msgs::OnionRealm0HopData {
3460                                         short_channel_id: 0x0101010101010101,
3461                                         amt_to_forward: 0x0100000001,
3462                                         outgoing_cltv_value: 0,
3463                                 },
3464                                 hmac: [0; 32],
3465                         },
3466                         msgs::OnionHopData {
3467                                 realm: 0,
3468                                 data: msgs::OnionRealm0HopData {
3469                                         short_channel_id: 0x0202020202020202,
3470                                         amt_to_forward: 0x0200000002,
3471                                         outgoing_cltv_value: 0,
3472                                 },
3473                                 hmac: [0; 32],
3474                         },
3475                         msgs::OnionHopData {
3476                                 realm: 0,
3477                                 data: msgs::OnionRealm0HopData {
3478                                         short_channel_id: 0x0303030303030303,
3479                                         amt_to_forward: 0x0300000003,
3480                                         outgoing_cltv_value: 0,
3481                                 },
3482                                 hmac: [0; 32],
3483                         },
3484                         msgs::OnionHopData {
3485                                 realm: 0,
3486                                 data: msgs::OnionRealm0HopData {
3487                                         short_channel_id: 0x0404040404040404,
3488                                         amt_to_forward: 0x0400000004,
3489                                         outgoing_cltv_value: 0,
3490                                 },
3491                                 hmac: [0; 32],
3492                         },
3493                 );
3494
3495                 let packet = ChannelManager::construct_onion_packet(payloads, onion_keys, &PaymentHash([0x42; 32]));
3496                 // Just check the final packet encoding, as it includes all the per-hop vectors in it
3497                 // anyway...
3498                 assert_eq!(packet.encode(), hex::decode("0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619e5f14350c2a76fc232b5e46d421e9615471ab9e0bc887beff8c95fdb878f7b3a716a996c7845c93d90e4ecbb9bde4ece2f69425c99e4bc820e44485455f135edc0d10f7d61ab590531cf08000179a333a347f8b4072f216400406bdf3bf038659793d4a1fd7b246979e3150a0a4cb052c9ec69acf0f48c3d39cd55675fe717cb7d80ce721caad69320c3a469a202f1e468c67eaf7a7cd8226d0fd32f7b48084dca885d56047694762b67021713ca673929c163ec36e04e40ca8e1c6d17569419d3039d9a1ec866abe044a9ad635778b961fc0776dc832b3a451bd5d35072d2269cf9b040f6b7a7dad84fb114ed413b1426cb96ceaf83825665ed5a1d002c1687f92465b49ed4c7f0218ff8c6c7dd7221d589c65b3b9aaa71a41484b122846c7c7b57e02e679ea8469b70e14fe4f70fee4d87b910cf144be6fe48eef24da475c0b0bcc6565ae82cd3f4e3b24c76eaa5616c6111343306ab35c1fe5ca4a77c0e314ed7dba39d6f1e0de791719c241a939cc493bea2bae1c1e932679ea94d29084278513c77b899cc98059d06a27d171b0dbdf6bee13ddc4fc17a0c4d2827d488436b57baa167544138ca2e64a11b43ac8a06cd0c2fba2d4d900ed2d9205305e2d7383cc98dacb078133de5f6fb6bed2ef26ba92cea28aafc3b9948dd9ae5559e8bd6920b8cea462aa445ca6a95e0e7ba52961b181c79e73bd581821df2b10173727a810c92b83b5ba4a0403eb710d2ca10689a35bec6c3a708e9e92f7d78ff3c5d9989574b00c6736f84c199256e76e19e78f0c98a9d580b4a658c84fc8f2096c2fbea8f5f8c59d0fdacb3be2802ef802abbecb3aba4acaac69a0e965abd8981e9896b1f6ef9d60f7a164b371af869fd0e48073742825e9434fc54da837e120266d53302954843538ea7c6c3dbfb4ff3b2fdbe244437f2a153ccf7bdb4c92aa08102d4f3cff2ae5ef86fab4653595e6a5837fa2f3e29f27a9cde5966843fb847a4a61f1e76c281fe8bb2b0a181d096100db5a1a5ce7a910238251a43ca556712eaadea167fb4d7d75825e440f3ecd782036d7574df8bceacb397abefc5f5254d2722215c53ff54af8299aaaad642c6d72a14d27882d9bbd539e1cc7a527526ba89b8c037ad09120e98ab042d3e8652b31ae0e478516bfaf88efca9f3676ffe99d2819dcaeb7610a626695f53117665d267d3f7abebd6bbd6733f645c72c389f03855bdf1e4b8075b516569b118233a0f0971d24b83113c0b096f5216a207ca99a7cddc81c130923fe3d91e7508c9ac5f2e914ff5dccab9e558566fa14efb34ac98d878580814b94b73acbfde9072f30b881f7f0fff42d4045d1ace6322d86a97d164aa84d93a60498065cc7c20e636f5862dc81531a88c60305a2e59a985be327a6902e4bed986dbf4a0b50c217af0ea7fdf9ab37f9ea1a1aaa72f54cf40154ea9b269f1a7c09f9f43245109431a175d50e2db0132337baa0ef97eed0fcf20489da36b79a1172faccc2f7ded7c60e00694282d93359c4682135642bc81f433574aa8ef0c97b4ade7ca372c5ffc23c7eddd839bab4e0f14d6df15c9dbeab176bec8b5701cf054eb3072f6dadc98f88819042bf10c407516ee58bce33fbe3b3d86a54255e577db4598e30a135361528c101683a5fcde7e8ba53f3456254be8f45fe3a56120ae96ea3773631fcb3873aa3abd91bcff00bd38bd43697a2e789e00da6077482e7b1b1a677b5afae4c54e6cbdf7377b694eb7d7a5b913476a5be923322d3de06060fd5e819635232a2cf4f0731da13b8546d1d6d4f8d75b9fce6c2341a71b0ea6f780df54bfdb0dd5cd9855179f602f9172307c7268724c3618e6817abd793adc214a0dc0bc616816632f27ea336fb56dfd").unwrap());
3499         }
3500
3501         #[test]
3502         fn test_failure_packet_onion() {
3503                 // Returning Errors test vectors from BOLT 4
3504
3505                 let onion_keys = build_test_onion_keys();
3506                 let onion_error = ChannelManager::build_failure_packet(&onion_keys[4].shared_secret[..], 0x2002, &[0; 0]);
3507                 assert_eq!(onion_error.encode(), hex::decode("4c2fc8bc08510334b6833ad9c3e79cd1b52ae59dfe5c2a4b23ead50f09f7ee0b0002200200fe0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap());
3508
3509                 let onion_packet_1 = ChannelManager::encrypt_failure_packet(&onion_keys[4].shared_secret[..], &onion_error.encode()[..]);
3510                 assert_eq!(onion_packet_1.data, hex::decode("a5e6bd0c74cb347f10cce367f949098f2457d14c046fd8a22cb96efb30b0fdcda8cb9168b50f2fd45edd73c1b0c8b33002df376801ff58aaa94000bf8a86f92620f343baef38a580102395ae3abf9128d1047a0736ff9b83d456740ebbb4aeb3aa9737f18fb4afb4aa074fb26c4d702f42968888550a3bded8c05247e045b866baef0499f079fdaeef6538f31d44deafffdfd3afa2fb4ca9082b8f1c465371a9894dd8c243fb4847e004f5256b3e90e2edde4c9fb3082ddfe4d1e734cacd96ef0706bf63c9984e22dc98851bcccd1c3494351feb458c9c6af41c0044bea3c47552b1d992ae542b17a2d0bba1a096c78d169034ecb55b6e3a7263c26017f033031228833c1daefc0dedb8cf7c3e37c9c37ebfe42f3225c326e8bcfd338804c145b16e34e4").unwrap());
3511
3512                 let onion_packet_2 = ChannelManager::encrypt_failure_packet(&onion_keys[3].shared_secret[..], &onion_packet_1.data[..]);
3513                 assert_eq!(onion_packet_2.data, hex::decode("c49a1ce81680f78f5f2000cda36268de34a3f0a0662f55b4e837c83a8773c22aa081bab1616a0011585323930fa5b9fae0c85770a2279ff59ec427ad1bbff9001c0cd1497004bd2a0f68b50704cf6d6a4bf3c8b6a0833399a24b3456961ba00736785112594f65b6b2d44d9f5ea4e49b5e1ec2af978cbe31c67114440ac51a62081df0ed46d4a3df295da0b0fe25c0115019f03f15ec86fabb4c852f83449e812f141a9395b3f70b766ebbd4ec2fae2b6955bd8f32684c15abfe8fd3a6261e52650e8807a92158d9f1463261a925e4bfba44bd20b166d532f0017185c3a6ac7957adefe45559e3072c8dc35abeba835a8cb01a71a15c736911126f27d46a36168ca5ef7dccd4e2886212602b181463e0dd30185c96348f9743a02aca8ec27c0b90dca270").unwrap());
3514
3515                 let onion_packet_3 = ChannelManager::encrypt_failure_packet(&onion_keys[2].shared_secret[..], &onion_packet_2.data[..]);
3516                 assert_eq!(onion_packet_3.data, hex::decode("a5d3e8634cfe78b2307d87c6d90be6fe7855b4f2cc9b1dfb19e92e4b79103f61ff9ac25f412ddfb7466e74f81b3e545563cdd8f5524dae873de61d7bdfccd496af2584930d2b566b4f8d3881f8c043df92224f38cf094cfc09d92655989531524593ec6d6caec1863bdfaa79229b5020acc034cd6deeea1021c50586947b9b8e6faa83b81fbfa6133c0af5d6b07c017f7158fa94f0d206baf12dda6b68f785b773b360fd0497e16cc402d779c8d48d0fa6315536ef0660f3f4e1865f5b38ea49c7da4fd959de4e83ff3ab686f059a45c65ba2af4a6a79166aa0f496bf04d06987b6d2ea205bdb0d347718b9aeff5b61dfff344993a275b79717cd815b6ad4c0beb568c4ac9c36ff1c315ec1119a1993c4b61e6eaa0375e0aaf738ac691abd3263bf937e3").unwrap());
3517
3518                 let onion_packet_4 = ChannelManager::encrypt_failure_packet(&onion_keys[1].shared_secret[..], &onion_packet_3.data[..]);
3519                 assert_eq!(onion_packet_4.data, hex::decode("aac3200c4968f56b21f53e5e374e3a2383ad2b1b6501bbcc45abc31e59b26881b7dfadbb56ec8dae8857add94e6702fb4c3a4de22e2e669e1ed926b04447fc73034bb730f4932acd62727b75348a648a1128744657ca6a4e713b9b646c3ca66cac02cdab44dd3439890ef3aaf61708714f7375349b8da541b2548d452d84de7084bb95b3ac2345201d624d31f4d52078aa0fa05a88b4e20202bd2b86ac5b52919ea305a8949de95e935eed0319cf3cf19ebea61d76ba92532497fcdc9411d06bcd4275094d0a4a3c5d3a945e43305a5a9256e333e1f64dbca5fcd4e03a39b9012d197506e06f29339dfee3331995b21615337ae060233d39befea925cc262873e0530408e6990f1cbd233a150ef7b004ff6166c70c68d9f8c853c1abca640b8660db2921").unwrap());
3520
3521                 let onion_packet_5 = ChannelManager::encrypt_failure_packet(&onion_keys[0].shared_secret[..], &onion_packet_4.data[..]);
3522                 assert_eq!(onion_packet_5.data, hex::decode("9c5add3963fc7f6ed7f148623c84134b5647e1306419dbe2174e523fa9e2fbed3a06a19f899145610741c83ad40b7712aefaddec8c6baf7325d92ea4ca4d1df8bce517f7e54554608bf2bd8071a4f52a7a2f7ffbb1413edad81eeea5785aa9d990f2865dc23b4bc3c301a94eec4eabebca66be5cf638f693ec256aec514620cc28ee4a94bd9565bc4d4962b9d3641d4278fb319ed2b84de5b665f307a2db0f7fbb757366067d88c50f7e829138fde4f78d39b5b5802f1b92a8a820865af5cc79f9f30bc3f461c66af95d13e5e1f0381c184572a91dee1c849048a647a1158cf884064deddbf1b0b88dfe2f791428d0ba0f6fb2f04e14081f69165ae66d9297c118f0907705c9c4954a199bae0bb96fad763d690e7daa6cfda59ba7f2c8d11448b604d12d").unwrap());
3523         }
3524
3525         fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
3526                 assert!(chain.does_match_tx(tx));
3527                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3528                 chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
3529                 for i in 2..100 {
3530                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3531                         chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
3532                 }
3533         }
3534
3535         struct Node {
3536                 chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
3537                 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
3538                 chan_monitor: Arc<test_utils::TestChannelMonitor>,
3539                 keys_manager: Arc<test_utils::TestKeysInterface>,
3540                 node: Arc<ChannelManager>,
3541                 router: Router,
3542                 node_seed: [u8; 32],
3543                 network_payment_count: Rc<RefCell<u8>>,
3544                 network_chan_count: Rc<RefCell<u32>>,
3545         }
3546         impl Drop for Node {
3547                 fn drop(&mut self) {
3548                         if !::std::thread::panicking() {
3549                                 // Check that we processed all pending events
3550                                 assert_eq!(self.node.get_and_clear_pending_msg_events().len(), 0);
3551                                 assert_eq!(self.node.get_and_clear_pending_events().len(), 0);
3552                                 assert_eq!(self.chan_monitor.added_monitors.lock().unwrap().len(), 0);
3553                         }
3554                 }
3555         }
3556
3557         fn create_chan_between_nodes(node_a: &Node, node_b: &Node) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3558                 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001)
3559         }
3560
3561         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) {
3562                 let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat);
3563                 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
3564                 (announcement, as_update, bs_update, channel_id, tx)
3565         }
3566
3567         macro_rules! get_revoke_commit_msgs {
3568                 ($node: expr, $node_id: expr) => {
3569                         {
3570                                 let events = $node.node.get_and_clear_pending_msg_events();
3571                                 assert_eq!(events.len(), 2);
3572                                 (match events[0] {
3573                                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3574                                                 assert_eq!(*node_id, $node_id);
3575                                                 (*msg).clone()
3576                                         },
3577                                         _ => panic!("Unexpected event"),
3578                                 }, match events[1] {
3579                                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3580                                                 assert_eq!(*node_id, $node_id);
3581                                                 assert!(updates.update_add_htlcs.is_empty());
3582                                                 assert!(updates.update_fulfill_htlcs.is_empty());
3583                                                 assert!(updates.update_fail_htlcs.is_empty());
3584                                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
3585                                                 assert!(updates.update_fee.is_none());
3586                                                 updates.commitment_signed.clone()
3587                                         },
3588                                         _ => panic!("Unexpected event"),
3589                                 })
3590                         }
3591                 }
3592         }
3593
3594         macro_rules! get_event_msg {
3595                 ($node: expr, $event_type: path, $node_id: expr) => {
3596                         {
3597                                 let events = $node.node.get_and_clear_pending_msg_events();
3598                                 assert_eq!(events.len(), 1);
3599                                 match events[0] {
3600                                         $event_type { ref node_id, ref msg } => {
3601                                                 assert_eq!(*node_id, $node_id);
3602                                                 (*msg).clone()
3603                                         },
3604                                         _ => panic!("Unexpected event"),
3605                                 }
3606                         }
3607                 }
3608         }
3609
3610         macro_rules! get_htlc_update_msgs {
3611                 ($node: expr, $node_id: expr) => {
3612                         {
3613                                 let events = $node.node.get_and_clear_pending_msg_events();
3614                                 assert_eq!(events.len(), 1);
3615                                 match events[0] {
3616                                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3617                                                 assert_eq!(*node_id, $node_id);
3618                                                 (*updates).clone()
3619                                         },
3620                                         _ => panic!("Unexpected event"),
3621                                 }
3622                         }
3623                 }
3624         }
3625
3626         macro_rules! get_feerate {
3627                 ($node: expr, $channel_id: expr) => {
3628                         {
3629                                 let chan_lock = $node.node.channel_state.lock().unwrap();
3630                                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
3631                                 chan.get_feerate()
3632                         }
3633                 }
3634         }
3635
3636
3637         fn create_chan_between_nodes_with_value_init(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> Transaction {
3638                 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
3639                 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();
3640                 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();
3641
3642                 let chan_id = *node_a.network_chan_count.borrow();
3643                 let tx;
3644                 let funding_output;
3645
3646                 let events_2 = node_a.node.get_and_clear_pending_events();
3647                 assert_eq!(events_2.len(), 1);
3648                 match events_2[0] {
3649                         Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
3650                                 assert_eq!(*channel_value_satoshis, channel_value);
3651                                 assert_eq!(user_channel_id, 42);
3652
3653                                 tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
3654                                         value: *channel_value_satoshis, script_pubkey: output_script.clone(),
3655                                 }]};
3656                                 funding_output = OutPoint::new(tx.txid(), 0);
3657
3658                                 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
3659                                 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3660                                 assert_eq!(added_monitors.len(), 1);
3661                                 assert_eq!(added_monitors[0].0, funding_output);
3662                                 added_monitors.clear();
3663                         },
3664                         _ => panic!("Unexpected event"),
3665                 }
3666
3667                 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();
3668                 {
3669                         let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
3670                         assert_eq!(added_monitors.len(), 1);
3671                         assert_eq!(added_monitors[0].0, funding_output);
3672                         added_monitors.clear();
3673                 }
3674
3675                 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();
3676                 {
3677                         let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3678                         assert_eq!(added_monitors.len(), 1);
3679                         assert_eq!(added_monitors[0].0, funding_output);
3680                         added_monitors.clear();
3681                 }
3682
3683                 let events_4 = node_a.node.get_and_clear_pending_events();
3684                 assert_eq!(events_4.len(), 1);
3685                 match events_4[0] {
3686                         Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
3687                                 assert_eq!(user_channel_id, 42);
3688                                 assert_eq!(*funding_txo, funding_output);
3689                         },
3690                         _ => panic!("Unexpected event"),
3691                 };
3692
3693                 tx
3694         }
3695
3696         fn create_chan_between_nodes_with_value_confirm(node_a: &Node, node_b: &Node, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
3697                 confirm_transaction(&node_b.chain_monitor, &tx, tx.version);
3698                 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();
3699
3700                 let channel_id;
3701
3702                 confirm_transaction(&node_a.chain_monitor, &tx, tx.version);
3703                 let events_6 = node_a.node.get_and_clear_pending_msg_events();
3704                 assert_eq!(events_6.len(), 2);
3705                 ((match events_6[0] {
3706                         MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3707                                 channel_id = msg.channel_id.clone();
3708                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
3709                                 msg.clone()
3710                         },
3711                         _ => panic!("Unexpected event"),
3712                 }, match events_6[1] {
3713                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3714                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
3715                                 msg.clone()
3716                         },
3717                         _ => panic!("Unexpected event"),
3718                 }), channel_id)
3719         }
3720
3721         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) {
3722                 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat);
3723                 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
3724                 (msgs, chan_id, tx)
3725         }
3726
3727         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) {
3728                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0).unwrap();
3729                 let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
3730                 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1).unwrap();
3731
3732                 let events_7 = node_b.node.get_and_clear_pending_msg_events();
3733                 assert_eq!(events_7.len(), 1);
3734                 let (announcement, bs_update) = match events_7[0] {
3735                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3736                                 (msg, update_msg)
3737                         },
3738                         _ => panic!("Unexpected event"),
3739                 };
3740
3741                 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs).unwrap();
3742                 let events_8 = node_a.node.get_and_clear_pending_msg_events();
3743                 assert_eq!(events_8.len(), 1);
3744                 let as_update = match events_8[0] {
3745                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3746                                 assert!(*announcement == *msg);
3747                                 assert_eq!(update_msg.contents.short_channel_id, announcement.contents.short_channel_id);
3748                                 assert_eq!(update_msg.contents.short_channel_id, bs_update.contents.short_channel_id);
3749                                 update_msg
3750                         },
3751                         _ => panic!("Unexpected event"),
3752                 };
3753
3754                 *node_a.network_chan_count.borrow_mut() += 1;
3755
3756                 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
3757         }
3758
3759         fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3760                 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001)
3761         }
3762
3763         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) {
3764                 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat);
3765                 for node in nodes {
3766                         assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
3767                         node.router.handle_channel_update(&chan_announcement.1).unwrap();
3768                         node.router.handle_channel_update(&chan_announcement.2).unwrap();
3769                 }
3770                 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
3771         }
3772
3773         macro_rules! check_spends {
3774                 ($tx: expr, $spends_tx: expr) => {
3775                         {
3776                                 let mut funding_tx_map = HashMap::new();
3777                                 let spends_tx = $spends_tx;
3778                                 funding_tx_map.insert(spends_tx.txid(), spends_tx);
3779                                 $tx.verify(&funding_tx_map).unwrap();
3780                         }
3781                 }
3782         }
3783
3784         macro_rules! get_closing_signed_broadcast {
3785                 ($node: expr, $dest_pubkey: expr) => {
3786                         {
3787                                 let events = $node.get_and_clear_pending_msg_events();
3788                                 assert!(events.len() == 1 || events.len() == 2);
3789                                 (match events[events.len() - 1] {
3790                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
3791                                                 assert_eq!(msg.contents.flags & 2, 2);
3792                                                 msg.clone()
3793                                         },
3794                                         _ => panic!("Unexpected event"),
3795                                 }, if events.len() == 2 {
3796                                         match events[0] {
3797                                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3798                                                         assert_eq!(*node_id, $dest_pubkey);
3799                                                         Some(msg.clone())
3800                                                 },
3801                                                 _ => panic!("Unexpected event"),
3802                                         }
3803                                 } else { None })
3804                         }
3805                 }
3806         }
3807
3808         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) {
3809                 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) };
3810                 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
3811                 let (tx_a, tx_b);
3812
3813                 node_a.close_channel(channel_id).unwrap();
3814                 node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id())).unwrap();
3815
3816                 let events_1 = node_b.get_and_clear_pending_msg_events();
3817                 assert!(events_1.len() >= 1);
3818                 let shutdown_b = match events_1[0] {
3819                         MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
3820                                 assert_eq!(node_id, &node_a.get_our_node_id());
3821                                 msg.clone()
3822                         },
3823                         _ => panic!("Unexpected event"),
3824                 };
3825
3826                 let closing_signed_b = if !close_inbound_first {
3827                         assert_eq!(events_1.len(), 1);
3828                         None
3829                 } else {
3830                         Some(match events_1[1] {
3831                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3832                                         assert_eq!(node_id, &node_a.get_our_node_id());
3833                                         msg.clone()
3834                                 },
3835                                 _ => panic!("Unexpected event"),
3836                         })
3837                 };
3838
3839                 node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b).unwrap();
3840                 let (as_update, bs_update) = if close_inbound_first {
3841                         assert!(node_a.get_and_clear_pending_msg_events().is_empty());
3842                         node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3843                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3844                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3845                         let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3846
3847                         node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
3848                         let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3849                         assert!(none_b.is_none());
3850                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3851                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3852                         (as_update, bs_update)
3853                 } else {
3854                         let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
3855
3856                         node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a).unwrap();
3857                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3858                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3859                         let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3860
3861                         node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3862                         let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3863                         assert!(none_a.is_none());
3864                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3865                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3866                         (as_update, bs_update)
3867                 };
3868                 assert_eq!(tx_a, tx_b);
3869                 check_spends!(tx_a, funding_tx);
3870
3871                 (as_update, bs_update, tx_a)
3872         }
3873
3874         struct SendEvent {
3875                 node_id: PublicKey,
3876                 msgs: Vec<msgs::UpdateAddHTLC>,
3877                 commitment_msg: msgs::CommitmentSigned,
3878         }
3879         impl SendEvent {
3880                 fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
3881                         assert!(updates.update_fulfill_htlcs.is_empty());
3882                         assert!(updates.update_fail_htlcs.is_empty());
3883                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3884                         assert!(updates.update_fee.is_none());
3885                         SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
3886                 }
3887
3888                 fn from_event(event: MessageSendEvent) -> SendEvent {
3889                         match event {
3890                                 MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
3891                                 _ => panic!("Unexpected event type!"),
3892                         }
3893                 }
3894
3895                 fn from_node(node: &Node) -> SendEvent {
3896                         let mut events = node.node.get_and_clear_pending_msg_events();
3897                         assert_eq!(events.len(), 1);
3898                         SendEvent::from_event(events.pop().unwrap())
3899                 }
3900         }
3901
3902         macro_rules! check_added_monitors {
3903                 ($node: expr, $count: expr) => {
3904                         {
3905                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
3906                                 assert_eq!(added_monitors.len(), $count);
3907                                 added_monitors.clear();
3908                         }
3909                 }
3910         }
3911
3912         macro_rules! commitment_signed_dance {
3913                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
3914                         {
3915                                 check_added_monitors!($node_a, 0);
3916                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3917                                 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3918                                 check_added_monitors!($node_a, 1);
3919                                 commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
3920                         }
3921                 };
3922                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
3923                         {
3924                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
3925                                 check_added_monitors!($node_b, 0);
3926                                 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3927                                 $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
3928                                 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3929                                 check_added_monitors!($node_b, 1);
3930                                 $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed).unwrap();
3931                                 let (bs_revoke_and_ack, extra_msg_option) = {
3932                                         let events = $node_b.node.get_and_clear_pending_msg_events();
3933                                         assert!(events.len() <= 2);
3934                                         (match events[0] {
3935                                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3936                                                         assert_eq!(*node_id, $node_a.node.get_our_node_id());
3937                                                         (*msg).clone()
3938                                                 },
3939                                                 _ => panic!("Unexpected event"),
3940                                         }, events.get(1).map(|e| e.clone()))
3941                                 };
3942                                 check_added_monitors!($node_b, 1);
3943                                 if $fail_backwards {
3944                                         assert!($node_a.node.get_and_clear_pending_events().is_empty());
3945                                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3946                                 }
3947                                 (extra_msg_option, bs_revoke_and_ack)
3948                         }
3949                 };
3950                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
3951                         {
3952                                 check_added_monitors!($node_a, 0);
3953                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3954                                 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3955                                 check_added_monitors!($node_a, 1);
3956                                 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
3957                                 assert!(extra_msg_option.is_none());
3958                                 bs_revoke_and_ack
3959                         }
3960                 };
3961                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
3962                         {
3963                                 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
3964                                 $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
3965                                 {
3966                                         let mut added_monitors = $node_a.chan_monitor.added_monitors.lock().unwrap();
3967                                         if $fail_backwards {
3968                                                 assert_eq!(added_monitors.len(), 2);
3969                                                 assert!(added_monitors[0].0 != added_monitors[1].0);
3970                                         } else {
3971                                                 assert_eq!(added_monitors.len(), 1);
3972                                         }
3973                                         added_monitors.clear();
3974                                 }
3975                                 extra_msg_option
3976                         }
3977                 };
3978                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
3979                         {
3980                                 assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
3981                         }
3982                 };
3983                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
3984                         {
3985                                 commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
3986                                 if $fail_backwards {
3987                                         let channel_state = $node_a.node.channel_state.lock().unwrap();
3988                                         assert_eq!(channel_state.pending_msg_events.len(), 1);
3989                                         if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
3990                                                 assert_ne!(*node_id, $node_b.node.get_our_node_id());
3991                                         } else { panic!("Unexpected event"); }
3992                                 } else {
3993                                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3994                                 }
3995                         }
3996                 }
3997         }
3998
3999         macro_rules! get_payment_preimage_hash {
4000                 ($node: expr) => {
4001                         {
4002                                 let payment_preimage = PaymentPreimage([*$node.network_payment_count.borrow(); 32]);
4003                                 *$node.network_payment_count.borrow_mut() += 1;
4004                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
4005                                 (payment_preimage, payment_hash)
4006                         }
4007                 }
4008         }
4009
4010         fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
4011                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4012
4013                 let mut payment_event = {
4014                         origin_node.node.send_payment(route, our_payment_hash).unwrap();
4015                         check_added_monitors!(origin_node, 1);
4016
4017                         let mut events = origin_node.node.get_and_clear_pending_msg_events();
4018                         assert_eq!(events.len(), 1);
4019                         SendEvent::from_event(events.remove(0))
4020                 };
4021                 let mut prev_node = origin_node;
4022
4023                 for (idx, &node) in expected_route.iter().enumerate() {
4024                         assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
4025
4026                         node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4027                         check_added_monitors!(node, 0);
4028                         commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
4029
4030                         let events_1 = node.node.get_and_clear_pending_events();
4031                         assert_eq!(events_1.len(), 1);
4032                         match events_1[0] {
4033                                 Event::PendingHTLCsForwardable { .. } => { },
4034                                 _ => panic!("Unexpected event"),
4035                         };
4036
4037                         node.node.channel_state.lock().unwrap().next_forward = Instant::now();
4038                         node.node.process_pending_htlc_forwards();
4039
4040                         if idx == expected_route.len() - 1 {
4041                                 let events_2 = node.node.get_and_clear_pending_events();
4042                                 assert_eq!(events_2.len(), 1);
4043                                 match events_2[0] {
4044                                         Event::PaymentReceived { ref payment_hash, amt } => {
4045                                                 assert_eq!(our_payment_hash, *payment_hash);
4046                                                 assert_eq!(amt, recv_value);
4047                                         },
4048                                         _ => panic!("Unexpected event"),
4049                                 }
4050                         } else {
4051                                 let mut events_2 = node.node.get_and_clear_pending_msg_events();
4052                                 assert_eq!(events_2.len(), 1);
4053                                 check_added_monitors!(node, 1);
4054                                 payment_event = SendEvent::from_event(events_2.remove(0));
4055                                 assert_eq!(payment_event.msgs.len(), 1);
4056                         }
4057
4058                         prev_node = node;
4059                 }
4060
4061                 (our_payment_preimage, our_payment_hash)
4062         }
4063
4064         fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: PaymentPreimage) {
4065                 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
4066                 check_added_monitors!(expected_route.last().unwrap(), 1);
4067
4068                 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
4069                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4070                 macro_rules! get_next_msgs {
4071                         ($node: expr) => {
4072                                 {
4073                                         let events = $node.node.get_and_clear_pending_msg_events();
4074                                         assert_eq!(events.len(), 1);
4075                                         match events[0] {
4076                                                 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 } } => {
4077                                                         assert!(update_add_htlcs.is_empty());
4078                                                         assert_eq!(update_fulfill_htlcs.len(), 1);
4079                                                         assert!(update_fail_htlcs.is_empty());
4080                                                         assert!(update_fail_malformed_htlcs.is_empty());
4081                                                         assert!(update_fee.is_none());
4082                                                         expected_next_node = node_id.clone();
4083                                                         Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()))
4084                                                 },
4085                                                 _ => panic!("Unexpected event"),
4086                                         }
4087                                 }
4088                         }
4089                 }
4090
4091                 macro_rules! last_update_fulfill_dance {
4092                         ($node: expr, $prev_node: expr) => {
4093                                 {
4094                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4095                                         check_added_monitors!($node, 0);
4096                                         assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4097                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4098                                 }
4099                         }
4100                 }
4101                 macro_rules! mid_update_fulfill_dance {
4102                         ($node: expr, $prev_node: expr, $new_msgs: expr) => {
4103                                 {
4104                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4105                                         check_added_monitors!($node, 1);
4106                                         let new_next_msgs = if $new_msgs {
4107                                                 get_next_msgs!($node)
4108                                         } else {
4109                                                 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4110                                                 None
4111                                         };
4112                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4113                                         next_msgs = new_next_msgs;
4114                                 }
4115                         }
4116                 }
4117
4118                 let mut prev_node = expected_route.last().unwrap();
4119                 for (idx, node) in expected_route.iter().rev().enumerate() {
4120                         assert_eq!(expected_next_node, node.node.get_our_node_id());
4121                         let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
4122                         if next_msgs.is_some() {
4123                                 mid_update_fulfill_dance!(node, prev_node, update_next_msgs);
4124                         } else if update_next_msgs {
4125                                 next_msgs = get_next_msgs!(node);
4126                         } else {
4127                                 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
4128                         }
4129                         if !skip_last && idx == expected_route.len() - 1 {
4130                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4131                         }
4132
4133                         prev_node = node;
4134                 }
4135
4136                 if !skip_last {
4137                         last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
4138                         let events = origin_node.node.get_and_clear_pending_events();
4139                         assert_eq!(events.len(), 1);
4140                         match events[0] {
4141                                 Event::PaymentSent { payment_preimage } => {
4142                                         assert_eq!(payment_preimage, our_payment_preimage);
4143                                 },
4144                                 _ => panic!("Unexpected event"),
4145                         }
4146                 }
4147         }
4148
4149         fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: PaymentPreimage) {
4150                 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage);
4151         }
4152
4153         const TEST_FINAL_CLTV: u32 = 32;
4154
4155         fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
4156                 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();
4157                 assert_eq!(route.hops.len(), expected_route.len());
4158                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4159                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
4160                 }
4161
4162                 send_along_route(origin_node, route, expected_route, recv_value)
4163         }
4164
4165         fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
4166                 let route = origin_node.router.get_route(&expected_route.last().unwrap().node.get_our_node_id(), None, &Vec::new(), recv_value, TEST_FINAL_CLTV).unwrap();
4167                 assert_eq!(route.hops.len(), expected_route.len());
4168                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4169                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
4170                 }
4171
4172                 let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4173
4174                 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
4175                 match err {
4176                         APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
4177                         _ => panic!("Unknown error variants"),
4178                 };
4179         }
4180
4181         fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
4182                 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
4183                 claim_payment(&origin, expected_route, our_payment_preimage);
4184         }
4185
4186         fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: PaymentHash) {
4187                 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash, 0));
4188                 check_added_monitors!(expected_route.last().unwrap(), 1);
4189
4190                 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
4191                 macro_rules! update_fail_dance {
4192                         ($node: expr, $prev_node: expr, $last_node: expr) => {
4193                                 {
4194                                         $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4195                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
4196                                 }
4197                         }
4198                 }
4199
4200                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4201                 let mut prev_node = expected_route.last().unwrap();
4202                 for (idx, node) in expected_route.iter().rev().enumerate() {
4203                         assert_eq!(expected_next_node, node.node.get_our_node_id());
4204                         if next_msgs.is_some() {
4205                                 // We may be the "last node" for the purpose of the commitment dance if we're
4206                                 // skipping the last node (implying it is disconnected) and we're the
4207                                 // second-to-last node!
4208                                 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
4209                         }
4210
4211                         let events = node.node.get_and_clear_pending_msg_events();
4212                         if !skip_last || idx != expected_route.len() - 1 {
4213                                 assert_eq!(events.len(), 1);
4214                                 match events[0] {
4215                                         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 } } => {
4216                                                 assert!(update_add_htlcs.is_empty());
4217                                                 assert!(update_fulfill_htlcs.is_empty());
4218                                                 assert_eq!(update_fail_htlcs.len(), 1);
4219                                                 assert!(update_fail_malformed_htlcs.is_empty());
4220                                                 assert!(update_fee.is_none());
4221                                                 expected_next_node = node_id.clone();
4222                                                 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
4223                                         },
4224                                         _ => panic!("Unexpected event"),
4225                                 }
4226                         } else {
4227                                 assert!(events.is_empty());
4228                         }
4229                         if !skip_last && idx == expected_route.len() - 1 {
4230                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4231                         }
4232
4233                         prev_node = node;
4234                 }
4235
4236                 if !skip_last {
4237                         update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
4238
4239                         let events = origin_node.node.get_and_clear_pending_events();
4240                         assert_eq!(events.len(), 1);
4241                         match events[0] {
4242                                 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
4243                                         assert_eq!(payment_hash, our_payment_hash);
4244                                         assert!(rejected_by_dest);
4245                                 },
4246                                 _ => panic!("Unexpected event"),
4247                         }
4248                 }
4249         }
4250
4251         fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: PaymentHash) {
4252                 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
4253         }
4254
4255         fn create_network(node_count: usize) -> Vec<Node> {
4256                 let mut nodes = Vec::new();
4257                 let mut rng = thread_rng();
4258                 let secp_ctx = Secp256k1::new();
4259
4260                 let chan_count = Rc::new(RefCell::new(0));
4261                 let payment_count = Rc::new(RefCell::new(0));
4262
4263                 for i in 0..node_count {
4264                         let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
4265                         let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
4266                         let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
4267                         let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
4268                         let mut seed = [0; 32];
4269                         rng.fill_bytes(&mut seed);
4270                         let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&seed, Network::Testnet, Arc::clone(&logger)));
4271                         let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone()));
4272                         let mut config = UserConfig::new();
4273                         config.channel_options.announced_channel = true;
4274                         config.channel_limits.force_announced_channel_preference = false;
4275                         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();
4276                         let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), chain_monitor.clone(), Arc::clone(&logger));
4277                         nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router, keys_manager, node_seed: seed,
4278                                 network_payment_count: payment_count.clone(),
4279                                 network_chan_count: chan_count.clone(),
4280                         });
4281                 }
4282
4283                 nodes
4284         }
4285
4286         #[test]
4287         fn test_async_inbound_update_fee() {
4288                 let mut nodes = create_network(2);
4289                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4290                 let channel_id = chan.2;
4291
4292                 // balancing
4293                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4294
4295                 // A                                        B
4296                 // update_fee                            ->
4297                 // send (1) commitment_signed            -.
4298                 //                                       <- update_add_htlc/commitment_signed
4299                 // send (2) RAA (awaiting remote revoke) -.
4300                 // (1) commitment_signed is delivered    ->
4301                 //                                       .- send (3) RAA (awaiting remote revoke)
4302                 // (2) RAA is delivered                  ->
4303                 //                                       .- send (4) commitment_signed
4304                 //                                       <- (3) RAA is delivered
4305                 // send (5) commitment_signed            -.
4306                 //                                       <- (4) commitment_signed is delivered
4307                 // send (6) RAA                          -.
4308                 // (5) commitment_signed is delivered    ->
4309                 //                                       <- RAA
4310                 // (6) RAA is delivered                  ->
4311
4312                 // First nodes[0] generates an update_fee
4313                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4314                 check_added_monitors!(nodes[0], 1);
4315
4316                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4317                 assert_eq!(events_0.len(), 1);
4318                 let (update_msg, commitment_signed) = match events_0[0] { // (1)
4319                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4320                                 (update_fee.as_ref(), commitment_signed)
4321                         },
4322                         _ => panic!("Unexpected event"),
4323                 };
4324
4325                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4326
4327                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4328                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4329                 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();
4330                 check_added_monitors!(nodes[1], 1);
4331
4332                 let payment_event = {
4333                         let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4334                         assert_eq!(events_1.len(), 1);
4335                         SendEvent::from_event(events_1.remove(0))
4336                 };
4337                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4338                 assert_eq!(payment_event.msgs.len(), 1);
4339
4340                 // ...now when the messages get delivered everyone should be happy
4341                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4342                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4343                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4344                 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4345                 check_added_monitors!(nodes[0], 1);
4346
4347                 // deliver(1), generate (3):
4348                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4349                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4350                 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
4351                 check_added_monitors!(nodes[1], 1);
4352
4353                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap(); // deliver (2)
4354                 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4355                 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
4356                 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
4357                 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
4358                 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
4359                 assert!(bs_update.update_fee.is_none()); // (4)
4360                 check_added_monitors!(nodes[1], 1);
4361
4362                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap(); // deliver (3)
4363                 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4364                 assert!(as_update.update_add_htlcs.is_empty()); // (5)
4365                 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
4366                 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
4367                 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
4368                 assert!(as_update.update_fee.is_none()); // (5)
4369                 check_added_monitors!(nodes[0], 1);
4370
4371                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed).unwrap(); // deliver (4)
4372                 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4373                 // only (6) so get_event_msg's assert(len == 1) passes
4374                 check_added_monitors!(nodes[0], 1);
4375
4376                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed).unwrap(); // deliver (5)
4377                 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4378                 check_added_monitors!(nodes[1], 1);
4379
4380                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4381                 check_added_monitors!(nodes[0], 1);
4382
4383                 let events_2 = nodes[0].node.get_and_clear_pending_events();
4384                 assert_eq!(events_2.len(), 1);
4385                 match events_2[0] {
4386                         Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
4387                         _ => panic!("Unexpected event"),
4388                 }
4389
4390                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap(); // deliver (6)
4391                 check_added_monitors!(nodes[1], 1);
4392         }
4393
4394         #[test]
4395         fn test_update_fee_unordered_raa() {
4396                 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
4397                 // crash in an earlier version of the update_fee patch)
4398                 let mut nodes = create_network(2);
4399                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4400                 let channel_id = chan.2;
4401
4402                 // balancing
4403                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4404
4405                 // First nodes[0] generates an update_fee
4406                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4407                 check_added_monitors!(nodes[0], 1);
4408
4409                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4410                 assert_eq!(events_0.len(), 1);
4411                 let update_msg = match events_0[0] { // (1)
4412                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
4413                                 update_fee.as_ref()
4414                         },
4415                         _ => panic!("Unexpected event"),
4416                 };
4417
4418                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4419
4420                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4421                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4422                 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();
4423                 check_added_monitors!(nodes[1], 1);
4424
4425                 let payment_event = {
4426                         let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4427                         assert_eq!(events_1.len(), 1);
4428                         SendEvent::from_event(events_1.remove(0))
4429                 };
4430                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4431                 assert_eq!(payment_event.msgs.len(), 1);
4432
4433                 // ...now when the messages get delivered everyone should be happy
4434                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4435                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4436                 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4437                 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4438                 check_added_monitors!(nodes[0], 1);
4439
4440                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap(); // deliver (2)
4441                 check_added_monitors!(nodes[1], 1);
4442
4443                 // We can't continue, sadly, because our (1) now has a bogus signature
4444         }
4445
4446         #[test]
4447         fn test_multi_flight_update_fee() {
4448                 let nodes = create_network(2);
4449                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4450                 let channel_id = chan.2;
4451
4452                 // A                                        B
4453                 // update_fee/commitment_signed          ->
4454                 //                                       .- send (1) RAA and (2) commitment_signed
4455                 // update_fee (never committed)          ->
4456                 // (3) update_fee                        ->
4457                 // We have to manually generate the above update_fee, it is allowed by the protocol but we
4458                 // don't track which updates correspond to which revoke_and_ack responses so we're in
4459                 // AwaitingRAA mode and will not generate the update_fee yet.
4460                 //                                       <- (1) RAA delivered
4461                 // (3) is generated and send (4) CS      -.
4462                 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
4463                 // know the per_commitment_point to use for it.
4464                 //                                       <- (2) commitment_signed delivered
4465                 // revoke_and_ack                        ->
4466                 //                                          B should send no response here
4467                 // (4) commitment_signed delivered       ->
4468                 //                                       <- RAA/commitment_signed delivered
4469                 // revoke_and_ack                        ->
4470
4471                 // First nodes[0] generates an update_fee
4472                 let initial_feerate = get_feerate!(nodes[0], channel_id);
4473                 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
4474                 check_added_monitors!(nodes[0], 1);
4475
4476                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4477                 assert_eq!(events_0.len(), 1);
4478                 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
4479                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4480                                 (update_fee.as_ref().unwrap(), commitment_signed)
4481                         },
4482                         _ => panic!("Unexpected event"),
4483                 };
4484
4485                 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
4486                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1).unwrap();
4487                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1).unwrap();
4488                 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4489                 check_added_monitors!(nodes[1], 1);
4490
4491                 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
4492                 // transaction:
4493                 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
4494                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4495                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4496
4497                 // Create the (3) update_fee message that nodes[0] will generate before it does...
4498                 let mut update_msg_2 = msgs::UpdateFee {
4499                         channel_id: update_msg_1.channel_id.clone(),
4500                         feerate_per_kw: (initial_feerate + 30) as u32,
4501                 };
4502
4503                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4504
4505                 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
4506                 // Deliver (3)
4507                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4508
4509                 // Deliver (1), generating (3) and (4)
4510                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap();
4511                 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4512                 check_added_monitors!(nodes[0], 1);
4513                 assert!(as_second_update.update_add_htlcs.is_empty());
4514                 assert!(as_second_update.update_fulfill_htlcs.is_empty());
4515                 assert!(as_second_update.update_fail_htlcs.is_empty());
4516                 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
4517                 // Check that the update_fee newly generated matches what we delivered:
4518                 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
4519                 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
4520
4521                 // Deliver (2) commitment_signed
4522                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
4523                 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4524                 check_added_monitors!(nodes[0], 1);
4525                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4526
4527                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap();
4528                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4529                 check_added_monitors!(nodes[1], 1);
4530
4531                 // Delever (4)
4532                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed).unwrap();
4533                 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4534                 check_added_monitors!(nodes[1], 1);
4535
4536                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4537                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4538                 check_added_monitors!(nodes[0], 1);
4539
4540                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment).unwrap();
4541                 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4542                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4543                 check_added_monitors!(nodes[0], 1);
4544
4545                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap();
4546                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4547                 check_added_monitors!(nodes[1], 1);
4548         }
4549
4550         #[test]
4551         fn test_update_fee_vanilla() {
4552                 let nodes = create_network(2);
4553                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4554                 let channel_id = chan.2;
4555
4556                 let feerate = get_feerate!(nodes[0], channel_id);
4557                 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
4558                 check_added_monitors!(nodes[0], 1);
4559
4560                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4561                 assert_eq!(events_0.len(), 1);
4562                 let (update_msg, commitment_signed) = match events_0[0] {
4563                                 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 } } => {
4564                                 (update_fee.as_ref(), commitment_signed)
4565                         },
4566                         _ => panic!("Unexpected event"),
4567                 };
4568                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4569
4570                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4571                 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4572                 check_added_monitors!(nodes[1], 1);
4573
4574                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4575                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4576                 check_added_monitors!(nodes[0], 1);
4577
4578                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4579                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4580                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4581                 check_added_monitors!(nodes[0], 1);
4582
4583                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4584                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4585                 check_added_monitors!(nodes[1], 1);
4586         }
4587
4588         #[test]
4589         fn test_update_fee_that_funder_cannot_afford() {
4590                 let nodes = create_network(2);
4591                 let channel_value = 1888;
4592                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000);
4593                 let channel_id = chan.2;
4594
4595                 let feerate = 260;
4596                 nodes[0].node.update_fee(channel_id, feerate).unwrap();
4597                 check_added_monitors!(nodes[0], 1);
4598                 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4599
4600                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap()).unwrap();
4601
4602                 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
4603
4604                 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
4605                 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
4606                 {
4607                         let chan_lock = nodes[1].node.channel_state.lock().unwrap();
4608                         let chan = chan_lock.by_id.get(&channel_id).unwrap();
4609
4610                         //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
4611                         let num_htlcs = chan.last_local_commitment_txn[0].output.len() - 2;
4612                         let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
4613                         let mut actual_fee = chan.last_local_commitment_txn[0].output.iter().fold(0, |acc, output| acc + output.value);
4614                         actual_fee = channel_value - actual_fee;
4615                         assert_eq!(total_fee, actual_fee);
4616                 } //drop the mutex
4617
4618                 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
4619                 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
4620                 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
4621                 check_added_monitors!(nodes[0], 1);
4622
4623                 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4624
4625                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap()).unwrap();
4626
4627                 //While producing the commitment_signed response after handling a received update_fee request the
4628                 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
4629                 //Should produce and error.
4630                 let err = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed).unwrap_err();
4631
4632                 assert!(match err.err {
4633                         "Funding remote cannot afford proposed new fee" => true,
4634                         _ => false,
4635                 });
4636
4637                 //clear the message we could not handle
4638                 nodes[1].node.get_and_clear_pending_msg_events();
4639         }
4640
4641         #[test]
4642         fn test_update_fee_with_fundee_update_add_htlc() {
4643                 let mut nodes = create_network(2);
4644                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4645                 let channel_id = chan.2;
4646
4647                 // balancing
4648                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4649
4650                 let feerate = get_feerate!(nodes[0], channel_id);
4651                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4652                 check_added_monitors!(nodes[0], 1);
4653
4654                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4655                 assert_eq!(events_0.len(), 1);
4656                 let (update_msg, commitment_signed) = match events_0[0] {
4657                                 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 } } => {
4658                                 (update_fee.as_ref(), commitment_signed)
4659                         },
4660                         _ => panic!("Unexpected event"),
4661                 };
4662                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4663                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4664                 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4665                 check_added_monitors!(nodes[1], 1);
4666
4667                 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
4668
4669                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
4670
4671                 // nothing happens since node[1] is in AwaitingRemoteRevoke
4672                 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
4673                 {
4674                         let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
4675                         assert_eq!(added_monitors.len(), 0);
4676                         added_monitors.clear();
4677                 }
4678                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4679                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4680                 // node[1] has nothing to do
4681
4682                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4683                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4684                 check_added_monitors!(nodes[0], 1);
4685
4686                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4687                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4688                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4689                 check_added_monitors!(nodes[0], 1);
4690                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4691                 check_added_monitors!(nodes[1], 1);
4692                 // AwaitingRemoteRevoke ends here
4693
4694                 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4695                 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
4696                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
4697                 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
4698                 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
4699                 assert_eq!(commitment_update.update_fee.is_none(), true);
4700
4701                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]).unwrap();
4702                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4703                 check_added_monitors!(nodes[0], 1);
4704                 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4705
4706                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke).unwrap();
4707                 check_added_monitors!(nodes[1], 1);
4708                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4709
4710                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed).unwrap();
4711                 check_added_monitors!(nodes[1], 1);
4712                 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4713                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4714
4715                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke).unwrap();
4716                 check_added_monitors!(nodes[0], 1);
4717                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4718
4719                 let events = nodes[0].node.get_and_clear_pending_events();
4720                 assert_eq!(events.len(), 1);
4721                 match events[0] {
4722                         Event::PendingHTLCsForwardable { .. } => { },
4723                         _ => panic!("Unexpected event"),
4724                 };
4725                 nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
4726                 nodes[0].node.process_pending_htlc_forwards();
4727
4728                 let events = nodes[0].node.get_and_clear_pending_events();
4729                 assert_eq!(events.len(), 1);
4730                 match events[0] {
4731                         Event::PaymentReceived { .. } => { },
4732                         _ => panic!("Unexpected event"),
4733                 };
4734
4735                 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
4736
4737                 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
4738                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
4739                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4740         }
4741
4742         #[test]
4743         fn test_update_fee() {
4744                 let nodes = create_network(2);
4745                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4746                 let channel_id = chan.2;
4747
4748                 // A                                        B
4749                 // (1) update_fee/commitment_signed      ->
4750                 //                                       <- (2) revoke_and_ack
4751                 //                                       .- send (3) commitment_signed
4752                 // (4) update_fee/commitment_signed      ->
4753                 //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
4754                 //                                       <- (3) commitment_signed delivered
4755                 // send (6) revoke_and_ack               -.
4756                 //                                       <- (5) deliver revoke_and_ack
4757                 // (6) deliver revoke_and_ack            ->
4758                 //                                       .- send (7) commitment_signed in response to (4)
4759                 //                                       <- (7) deliver commitment_signed
4760                 // revoke_and_ack                        ->
4761
4762                 // Create and deliver (1)...
4763                 let feerate = get_feerate!(nodes[0], channel_id);
4764                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4765                 check_added_monitors!(nodes[0], 1);
4766
4767                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4768                 assert_eq!(events_0.len(), 1);
4769                 let (update_msg, commitment_signed) = match events_0[0] {
4770                                 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 } } => {
4771                                 (update_fee.as_ref(), commitment_signed)
4772                         },
4773                         _ => panic!("Unexpected event"),
4774                 };
4775                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4776
4777                 // Generate (2) and (3):
4778                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4779                 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4780                 check_added_monitors!(nodes[1], 1);
4781
4782                 // Deliver (2):
4783                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4784                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4785                 check_added_monitors!(nodes[0], 1);
4786
4787                 // Create and deliver (4)...
4788                 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
4789                 check_added_monitors!(nodes[0], 1);
4790                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4791                 assert_eq!(events_0.len(), 1);
4792                 let (update_msg, commitment_signed) = match events_0[0] {
4793                                 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 } } => {
4794                                 (update_fee.as_ref(), commitment_signed)
4795                         },
4796                         _ => panic!("Unexpected event"),
4797                 };
4798
4799                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4800                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4801                 check_added_monitors!(nodes[1], 1);
4802                 // ... creating (5)
4803                 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4804                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4805
4806                 // Handle (3), creating (6):
4807                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0).unwrap();
4808                 check_added_monitors!(nodes[0], 1);
4809                 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4810                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4811
4812                 // Deliver (5):
4813                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4814                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4815                 check_added_monitors!(nodes[0], 1);
4816
4817                 // Deliver (6), creating (7):
4818                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0).unwrap();
4819                 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4820                 assert!(commitment_update.update_add_htlcs.is_empty());
4821                 assert!(commitment_update.update_fulfill_htlcs.is_empty());
4822                 assert!(commitment_update.update_fail_htlcs.is_empty());
4823                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
4824                 assert!(commitment_update.update_fee.is_none());
4825                 check_added_monitors!(nodes[1], 1);
4826
4827                 // Deliver (7)
4828                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4829                 check_added_monitors!(nodes[0], 1);
4830                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4831                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4832
4833                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4834                 check_added_monitors!(nodes[1], 1);
4835                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4836
4837                 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
4838                 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
4839                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4840         }
4841
4842         #[test]
4843         fn pre_funding_lock_shutdown_test() {
4844                 // Test sending a shutdown prior to funding_locked after funding generation
4845                 let nodes = create_network(2);
4846                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0);
4847                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4848                 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4849                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4850
4851                 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
4852                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4853                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4854                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4855                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4856
4857                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4858                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4859                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4860                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4861                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4862                 assert!(node_0_none.is_none());
4863
4864                 assert!(nodes[0].node.list_channels().is_empty());
4865                 assert!(nodes[1].node.list_channels().is_empty());
4866         }
4867
4868         #[test]
4869         fn updates_shutdown_wait() {
4870                 // Test sending a shutdown with outstanding updates pending
4871                 let mut nodes = create_network(3);
4872                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4873                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4874                 let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4875                 let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4876
4877                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
4878
4879                 nodes[0].node.close_channel(&chan_1.2).unwrap();
4880                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4881                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4882                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4883                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4884
4885                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4886                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4887
4888                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4889                 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route_1, payment_hash) {}
4890                 else { panic!("New sends should fail!") };
4891                 if let Err(APIError::ChannelUnavailable {..}) = nodes[1].node.send_payment(route_2, payment_hash) {}
4892                 else { panic!("New sends should fail!") };
4893
4894                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
4895                 check_added_monitors!(nodes[2], 1);
4896                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4897                 assert!(updates.update_add_htlcs.is_empty());
4898                 assert!(updates.update_fail_htlcs.is_empty());
4899                 assert!(updates.update_fail_malformed_htlcs.is_empty());
4900                 assert!(updates.update_fee.is_none());
4901                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4902                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
4903                 check_added_monitors!(nodes[1], 1);
4904                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4905                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
4906
4907                 assert!(updates_2.update_add_htlcs.is_empty());
4908                 assert!(updates_2.update_fail_htlcs.is_empty());
4909                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
4910                 assert!(updates_2.update_fee.is_none());
4911                 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
4912                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
4913                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
4914
4915                 let events = nodes[0].node.get_and_clear_pending_events();
4916                 assert_eq!(events.len(), 1);
4917                 match events[0] {
4918                         Event::PaymentSent { ref payment_preimage } => {
4919                                 assert_eq!(our_payment_preimage, *payment_preimage);
4920                         },
4921                         _ => panic!("Unexpected event"),
4922                 }
4923
4924                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4925                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4926                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4927                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4928                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4929                 assert!(node_0_none.is_none());
4930
4931                 assert!(nodes[0].node.list_channels().is_empty());
4932
4933                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4934                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
4935                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
4936                 assert!(nodes[1].node.list_channels().is_empty());
4937                 assert!(nodes[2].node.list_channels().is_empty());
4938         }
4939
4940         #[test]
4941         fn htlc_fail_async_shutdown() {
4942                 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
4943                 let mut nodes = create_network(3);
4944                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4945                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4946
4947                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4948                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4949                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
4950                 check_added_monitors!(nodes[0], 1);
4951                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4952                 assert_eq!(updates.update_add_htlcs.len(), 1);
4953                 assert!(updates.update_fulfill_htlcs.is_empty());
4954                 assert!(updates.update_fail_htlcs.is_empty());
4955                 assert!(updates.update_fail_malformed_htlcs.is_empty());
4956                 assert!(updates.update_fee.is_none());
4957
4958                 nodes[1].node.close_channel(&chan_1.2).unwrap();
4959                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4960                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4961                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4962
4963                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
4964                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
4965                 check_added_monitors!(nodes[1], 1);
4966                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4967                 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
4968
4969                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4970                 assert!(updates_2.update_add_htlcs.is_empty());
4971                 assert!(updates_2.update_fulfill_htlcs.is_empty());
4972                 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
4973                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
4974                 assert!(updates_2.update_fee.is_none());
4975
4976                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]).unwrap();
4977                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
4978
4979                 let events = nodes[0].node.get_and_clear_pending_events();
4980                 assert_eq!(events.len(), 1);
4981                 match events[0] {
4982                         Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } => {
4983                                 assert_eq!(our_payment_hash, *payment_hash);
4984                                 assert!(!rejected_by_dest);
4985                         },
4986                         _ => panic!("Unexpected event"),
4987                 }
4988
4989                 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4990                 assert_eq!(msg_events.len(), 2);
4991                 let node_0_closing_signed = match msg_events[0] {
4992                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
4993                                 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
4994                                 (*msg).clone()
4995                         },
4996                         _ => panic!("Unexpected event"),
4997                 };
4998                 match msg_events[1] {
4999                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
5000                                 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
5001                         },
5002                         _ => panic!("Unexpected event"),
5003                 }
5004
5005                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5006                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5007                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5008                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5009                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5010                 assert!(node_0_none.is_none());
5011
5012                 assert!(nodes[0].node.list_channels().is_empty());
5013
5014                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5015                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5016                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5017                 assert!(nodes[1].node.list_channels().is_empty());
5018                 assert!(nodes[2].node.list_channels().is_empty());
5019         }
5020
5021         fn do_test_shutdown_rebroadcast(recv_count: u8) {
5022                 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
5023                 // messages delivered prior to disconnect
5024                 let nodes = create_network(3);
5025                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5026                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5027
5028                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
5029
5030                 nodes[1].node.close_channel(&chan_1.2).unwrap();
5031                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5032                 if recv_count > 0 {
5033                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
5034                         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5035                         if recv_count > 1 {
5036                                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
5037                         }
5038                 }
5039
5040                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5041                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5042
5043                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5044                 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5045                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5046                 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5047
5048                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish).unwrap();
5049                 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5050                 assert!(node_1_shutdown == node_1_2nd_shutdown);
5051
5052                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish).unwrap();
5053                 let node_0_2nd_shutdown = if recv_count > 0 {
5054                         let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5055                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5056                         node_0_2nd_shutdown
5057                 } else {
5058                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5059                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5060                         get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
5061                 };
5062                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown).unwrap();
5063
5064                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5065                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5066
5067                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
5068                 check_added_monitors!(nodes[2], 1);
5069                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5070                 assert!(updates.update_add_htlcs.is_empty());
5071                 assert!(updates.update_fail_htlcs.is_empty());
5072                 assert!(updates.update_fail_malformed_htlcs.is_empty());
5073                 assert!(updates.update_fee.is_none());
5074                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5075                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
5076                 check_added_monitors!(nodes[1], 1);
5077                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5078                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
5079
5080                 assert!(updates_2.update_add_htlcs.is_empty());
5081                 assert!(updates_2.update_fail_htlcs.is_empty());
5082                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
5083                 assert!(updates_2.update_fee.is_none());
5084                 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
5085                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
5086                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
5087
5088                 let events = nodes[0].node.get_and_clear_pending_events();
5089                 assert_eq!(events.len(), 1);
5090                 match events[0] {
5091                         Event::PaymentSent { ref payment_preimage } => {
5092                                 assert_eq!(our_payment_preimage, *payment_preimage);
5093                         },
5094                         _ => panic!("Unexpected event"),
5095                 }
5096
5097                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5098                 if recv_count > 0 {
5099                         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5100                         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5101                         assert!(node_1_closing_signed.is_some());
5102                 }
5103
5104                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5105                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5106
5107                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5108                 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5109                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5110                 if recv_count == 0 {
5111                         // If all closing_signeds weren't delivered we can just resume where we left off...
5112                         let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5113
5114                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish).unwrap();
5115                         let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5116                         assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
5117
5118                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish).unwrap();
5119                         let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5120                         assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
5121
5122                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown).unwrap();
5123                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5124
5125                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown).unwrap();
5126                         let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5127                         assert!(node_0_closing_signed == node_0_2nd_closing_signed);
5128
5129                         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed).unwrap();
5130                         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5131                         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5132                         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5133                         assert!(node_0_none.is_none());
5134                 } else {
5135                         // If one node, however, received + responded with an identical closing_signed we end
5136                         // up erroring and node[0] will try to broadcast its own latest commitment transaction.
5137                         // There isn't really anything better we can do simply, but in the future we might
5138                         // explore storing a set of recently-closed channels that got disconnected during
5139                         // closing_signed and avoiding broadcasting local commitment txn for some timeout to
5140                         // give our counterparty enough time to (potentially) broadcast a cooperative closing
5141                         // transaction.
5142                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5143
5144                         if let Err(msgs::HandleError{action: Some(msgs::ErrorAction::SendErrorMessage{msg}), ..}) =
5145                                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish) {
5146                                 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
5147                                 let msgs::ErrorMessage {ref channel_id, ..} = msg;
5148                                 assert_eq!(*channel_id, chan_1.2);
5149                         } else { panic!("Needed SendErrorMessage close"); }
5150
5151                         // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
5152                         // checks it, but in this case nodes[0] didn't ever get a chance to receive a
5153                         // closing_signed so we do it ourselves
5154                         let events = nodes[0].node.get_and_clear_pending_msg_events();
5155                         assert_eq!(events.len(), 1);
5156                         match events[0] {
5157                                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5158                                         assert_eq!(msg.contents.flags & 2, 2);
5159                                 },
5160                                 _ => panic!("Unexpected event"),
5161                         }
5162                 }
5163
5164                 assert!(nodes[0].node.list_channels().is_empty());
5165
5166                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5167                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5168                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5169                 assert!(nodes[1].node.list_channels().is_empty());
5170                 assert!(nodes[2].node.list_channels().is_empty());
5171         }
5172
5173         #[test]
5174         fn test_shutdown_rebroadcast() {
5175                 do_test_shutdown_rebroadcast(0);
5176                 do_test_shutdown_rebroadcast(1);
5177                 do_test_shutdown_rebroadcast(2);
5178         }
5179
5180         #[test]
5181         fn fake_network_test() {
5182                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5183                 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
5184                 let nodes = create_network(4);
5185
5186                 // Create some initial channels
5187                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5188                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5189                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5190
5191                 // Rebalance the network a bit by relaying one payment through all the channels...
5192                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5193                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5194                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5195                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5196
5197                 // Send some more payments
5198                 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
5199                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
5200                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
5201
5202                 // Test failure packets
5203                 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
5204                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
5205
5206                 // Add a new channel that skips 3
5207                 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
5208
5209                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
5210                 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
5211                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5212                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5213                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5214                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5215                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5216
5217                 // Do some rebalance loop payments, simultaneously
5218                 let mut hops = Vec::with_capacity(3);
5219                 hops.push(RouteHop {
5220                         pubkey: nodes[2].node.get_our_node_id(),
5221                         short_channel_id: chan_2.0.contents.short_channel_id,
5222                         fee_msat: 0,
5223                         cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
5224                 });
5225                 hops.push(RouteHop {
5226                         pubkey: nodes[3].node.get_our_node_id(),
5227                         short_channel_id: chan_3.0.contents.short_channel_id,
5228                         fee_msat: 0,
5229                         cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
5230                 });
5231                 hops.push(RouteHop {
5232                         pubkey: nodes[1].node.get_our_node_id(),
5233                         short_channel_id: chan_4.0.contents.short_channel_id,
5234                         fee_msat: 1000000,
5235                         cltv_expiry_delta: TEST_FINAL_CLTV,
5236                 });
5237                 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;
5238                 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;
5239                 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
5240
5241                 let mut hops = Vec::with_capacity(3);
5242                 hops.push(RouteHop {
5243                         pubkey: nodes[3].node.get_our_node_id(),
5244                         short_channel_id: chan_4.0.contents.short_channel_id,
5245                         fee_msat: 0,
5246                         cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
5247                 });
5248                 hops.push(RouteHop {
5249                         pubkey: nodes[2].node.get_our_node_id(),
5250                         short_channel_id: chan_3.0.contents.short_channel_id,
5251                         fee_msat: 0,
5252                         cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
5253                 });
5254                 hops.push(RouteHop {
5255                         pubkey: nodes[1].node.get_our_node_id(),
5256                         short_channel_id: chan_2.0.contents.short_channel_id,
5257                         fee_msat: 1000000,
5258                         cltv_expiry_delta: TEST_FINAL_CLTV,
5259                 });
5260                 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;
5261                 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;
5262                 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
5263
5264                 // Claim the rebalances...
5265                 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
5266                 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
5267
5268                 // Add a duplicate new channel from 2 to 4
5269                 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3);
5270
5271                 // Send some payments across both channels
5272                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5273                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5274                 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5275
5276                 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
5277
5278                 //TODO: Test that routes work again here as we've been notified that the channel is full
5279
5280                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
5281                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
5282                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
5283
5284                 // Close down the channels...
5285                 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
5286                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
5287                 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
5288                 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
5289                 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
5290         }
5291
5292         #[test]
5293         fn duplicate_htlc_test() {
5294                 // Test that we accept duplicate payment_hash HTLCs across the network and that
5295                 // claiming/failing them are all separate and don't effect each other
5296                 let mut nodes = create_network(6);
5297
5298                 // Create some initial channels to route via 3 to 4/5 from 0/1/2
5299                 create_announced_chan_between_nodes(&nodes, 0, 3);
5300                 create_announced_chan_between_nodes(&nodes, 1, 3);
5301                 create_announced_chan_between_nodes(&nodes, 2, 3);
5302                 create_announced_chan_between_nodes(&nodes, 3, 4);
5303                 create_announced_chan_between_nodes(&nodes, 3, 5);
5304
5305                 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
5306
5307                 *nodes[0].network_payment_count.borrow_mut() -= 1;
5308                 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
5309
5310                 *nodes[0].network_payment_count.borrow_mut() -= 1;
5311                 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
5312
5313                 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
5314                 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
5315                 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
5316         }
5317
5318         #[derive(PartialEq)]
5319         enum HTLCType { NONE, TIMEOUT, SUCCESS }
5320         /// Tests that the given node has broadcast transactions for the given Channel
5321         ///
5322         /// First checks that the latest local commitment tx has been broadcast, unless an explicit
5323         /// commitment_tx is provided, which may be used to test that a remote commitment tx was
5324         /// broadcast and the revoked outputs were claimed.
5325         ///
5326         /// Next tests that there is (or is not) a transaction that spends the commitment transaction
5327         /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
5328         ///
5329         /// All broadcast transactions must be accounted for in one of the above three types of we'll
5330         /// also fail.
5331         fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
5332                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5333                 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
5334
5335                 let mut res = Vec::with_capacity(2);
5336                 node_txn.retain(|tx| {
5337                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
5338                                 check_spends!(tx, chan.3.clone());
5339                                 if commitment_tx.is_none() {
5340                                         res.push(tx.clone());
5341                                 }
5342                                 false
5343                         } else { true }
5344                 });
5345                 if let Some(explicit_tx) = commitment_tx {
5346                         res.push(explicit_tx.clone());
5347                 }
5348
5349                 assert_eq!(res.len(), 1);
5350
5351                 if has_htlc_tx != HTLCType::NONE {
5352                         node_txn.retain(|tx| {
5353                                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
5354                                         check_spends!(tx, res[0].clone());
5355                                         if has_htlc_tx == HTLCType::TIMEOUT {
5356                                                 assert!(tx.lock_time != 0);
5357                                         } else {
5358                                                 assert!(tx.lock_time == 0);
5359                                         }
5360                                         res.push(tx.clone());
5361                                         false
5362                                 } else { true }
5363                         });
5364                         assert!(res.len() == 2 || res.len() == 3);
5365                         if res.len() == 3 {
5366                                 assert_eq!(res[1], res[2]);
5367                         }
5368                 }
5369
5370                 assert!(node_txn.is_empty());
5371                 res
5372         }
5373
5374         /// Tests that the given node has broadcast a claim transaction against the provided revoked
5375         /// HTLC transaction.
5376         fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
5377                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5378                 assert_eq!(node_txn.len(), 1);
5379                 node_txn.retain(|tx| {
5380                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
5381                                 check_spends!(tx, revoked_tx.clone());
5382                                 false
5383                         } else { true }
5384                 });
5385                 assert!(node_txn.is_empty());
5386         }
5387
5388         fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
5389                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5390
5391                 assert!(node_txn.len() >= 1);
5392                 assert_eq!(node_txn[0].input.len(), 1);
5393                 let mut found_prev = false;
5394
5395                 for tx in prev_txn {
5396                         if node_txn[0].input[0].previous_output.txid == tx.txid() {
5397                                 check_spends!(node_txn[0], tx.clone());
5398                                 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
5399                                 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
5400
5401                                 found_prev = true;
5402                                 break;
5403                         }
5404                 }
5405                 assert!(found_prev);
5406
5407                 let mut res = Vec::new();
5408                 mem::swap(&mut *node_txn, &mut res);
5409                 res
5410         }
5411
5412         fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
5413                 let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
5414                 assert_eq!(events_1.len(), 1);
5415                 let as_update = match events_1[0] {
5416                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5417                                 msg.clone()
5418                         },
5419                         _ => panic!("Unexpected event"),
5420                 };
5421
5422                 let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
5423                 assert_eq!(events_2.len(), 1);
5424                 let bs_update = match events_2[0] {
5425                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5426                                 msg.clone()
5427                         },
5428                         _ => panic!("Unexpected event"),
5429                 };
5430
5431                 for node in nodes {
5432                         node.router.handle_channel_update(&as_update).unwrap();
5433                         node.router.handle_channel_update(&bs_update).unwrap();
5434                 }
5435         }
5436
5437         macro_rules! expect_pending_htlcs_forwardable {
5438                 ($node: expr) => {{
5439                         let events = $node.node.get_and_clear_pending_events();
5440                         assert_eq!(events.len(), 1);
5441                         match events[0] {
5442                                 Event::PendingHTLCsForwardable { .. } => { },
5443                                 _ => panic!("Unexpected event"),
5444                         };
5445                         $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
5446                         $node.node.process_pending_htlc_forwards();
5447                 }}
5448         }
5449
5450         fn do_channel_reserve_test(test_recv: bool) {
5451                 use util::rng;
5452                 use std::sync::atomic::Ordering;
5453                 use ln::msgs::HandleError;
5454
5455                 macro_rules! get_channel_value_stat {
5456                         ($node: expr, $channel_id: expr) => {{
5457                                 let chan_lock = $node.node.channel_state.lock().unwrap();
5458                                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
5459                                 chan.get_value_stat()
5460                         }}
5461                 }
5462
5463                 let mut nodes = create_network(3);
5464                 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001);
5465                 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001);
5466
5467                 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
5468                 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
5469
5470                 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
5471                 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
5472
5473                 macro_rules! get_route_and_payment_hash {
5474                         ($recv_value: expr) => {{
5475                                 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
5476                                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5477                                 (route, payment_hash, payment_preimage)
5478                         }}
5479                 };
5480
5481                 macro_rules! expect_forward {
5482                         ($node: expr) => {{
5483                                 let mut events = $node.node.get_and_clear_pending_msg_events();
5484                                 assert_eq!(events.len(), 1);
5485                                 check_added_monitors!($node, 1);
5486                                 let payment_event = SendEvent::from_event(events.remove(0));
5487                                 payment_event
5488                         }}
5489                 }
5490
5491                 macro_rules! expect_payment_received {
5492                         ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
5493                                 let events = $node.node.get_and_clear_pending_events();
5494                                 assert_eq!(events.len(), 1);
5495                                 match events[0] {
5496                                         Event::PaymentReceived { ref payment_hash, amt } => {
5497                                                 assert_eq!($expected_payment_hash, *payment_hash);
5498                                                 assert_eq!($expected_recv_value, amt);
5499                                         },
5500                                         _ => panic!("Unexpected event"),
5501                                 }
5502                         }
5503                 };
5504
5505                 let feemsat = 239; // somehow we know?
5506                 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
5507
5508                 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
5509
5510                 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
5511                 {
5512                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
5513                         assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
5514                         let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
5515                         match err {
5516                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
5517                                 _ => panic!("Unknown error variants"),
5518                         }
5519                 }
5520
5521                 let mut htlc_id = 0;
5522                 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
5523                 // nodes[0]'s wealth
5524                 loop {
5525                         let amt_msat = recv_value_0 + total_fee_msat;
5526                         if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
5527                                 break;
5528                         }
5529                         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
5530                         htlc_id += 1;
5531
5532                         let (stat01_, stat11_, stat12_, stat22_) = (
5533                                 get_channel_value_stat!(nodes[0], chan_1.2),
5534                                 get_channel_value_stat!(nodes[1], chan_1.2),
5535                                 get_channel_value_stat!(nodes[1], chan_2.2),
5536                                 get_channel_value_stat!(nodes[2], chan_2.2),
5537                         );
5538
5539                         assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
5540                         assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
5541                         assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
5542                         assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
5543                         stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
5544                 }
5545
5546                 {
5547                         let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
5548                         // attempt to get channel_reserve violation
5549                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
5550                         let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
5551                         match err {
5552                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5553                                 _ => panic!("Unknown error variants"),
5554                         }
5555                 }
5556
5557                 // adding pending output
5558                 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
5559                 let amt_msat_1 = recv_value_1 + total_fee_msat;
5560
5561                 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
5562                 let payment_event_1 = {
5563                         nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
5564                         check_added_monitors!(nodes[0], 1);
5565
5566                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5567                         assert_eq!(events.len(), 1);
5568                         SendEvent::from_event(events.remove(0))
5569                 };
5570                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]).unwrap();
5571
5572                 // channel reserve test with htlc pending output > 0
5573                 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
5574                 {
5575                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5576                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5577                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5578                                 _ => panic!("Unknown error variants"),
5579                         }
5580                 }
5581
5582                 {
5583                         // test channel_reserve test on nodes[1] side
5584                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5585
5586                         // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
5587                         let secp_ctx = Secp256k1::new();
5588                         let session_priv = SecretKey::from_slice(&secp_ctx, &{
5589                                 let mut session_key = [0; 32];
5590                                 rng::fill_bytes(&mut session_key);
5591                                 session_key
5592                         }).expect("RNG is bad!");
5593
5594                         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5595                         let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
5596                         let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height).unwrap();
5597                         let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
5598                         let msg = msgs::UpdateAddHTLC {
5599                                 channel_id: chan_1.2,
5600                                 htlc_id,
5601                                 amount_msat: htlc_msat,
5602                                 payment_hash: our_payment_hash,
5603                                 cltv_expiry: htlc_cltv,
5604                                 onion_routing_packet: onion_packet,
5605                         };
5606
5607                         if test_recv {
5608                                 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).err().unwrap();
5609                                 match err {
5610                                         HandleError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
5611                                 }
5612                                 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
5613                                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5614                                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5615                                 let channel_close_broadcast = nodes[1].node.get_and_clear_pending_msg_events();
5616                                 assert_eq!(channel_close_broadcast.len(), 1);
5617                                 match channel_close_broadcast[0] {
5618                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5619                                                 assert_eq!(msg.contents.flags & 2, 2);
5620                                         },
5621                                         _ => panic!("Unexpected event"),
5622                                 }
5623                                 return;
5624                         }
5625                 }
5626
5627                 // split the rest to test holding cell
5628                 let recv_value_21 = recv_value_2/2;
5629                 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
5630                 {
5631                         let stat = get_channel_value_stat!(nodes[0], chan_1.2);
5632                         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);
5633                 }
5634
5635                 // now see if they go through on both sides
5636                 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
5637                 // but this will stuck in the holding cell
5638                 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
5639                 check_added_monitors!(nodes[0], 0);
5640                 let events = nodes[0].node.get_and_clear_pending_events();
5641                 assert_eq!(events.len(), 0);
5642
5643                 // test with outbound holding cell amount > 0
5644                 {
5645                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
5646                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5647                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5648                                 _ => panic!("Unknown error variants"),
5649                         }
5650                 }
5651
5652                 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
5653                 // this will also stuck in the holding cell
5654                 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
5655                 check_added_monitors!(nodes[0], 0);
5656                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
5657                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5658
5659                 // flush the pending htlc
5660                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg).unwrap();
5661                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5662                 check_added_monitors!(nodes[1], 1);
5663
5664                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
5665                 check_added_monitors!(nodes[0], 1);
5666                 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5667
5668                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed).unwrap();
5669                 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
5670                 // No commitment_signed so get_event_msg's assert(len == 1) passes
5671                 check_added_monitors!(nodes[0], 1);
5672
5673                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
5674                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5675                 check_added_monitors!(nodes[1], 1);
5676
5677                 expect_pending_htlcs_forwardable!(nodes[1]);
5678
5679                 let ref payment_event_11 = expect_forward!(nodes[1]);
5680                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]).unwrap();
5681                 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
5682
5683                 expect_pending_htlcs_forwardable!(nodes[2]);
5684                 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
5685
5686                 // flush the htlcs in the holding cell
5687                 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
5688                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]).unwrap();
5689                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]).unwrap();
5690                 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
5691                 expect_pending_htlcs_forwardable!(nodes[1]);
5692
5693                 let ref payment_event_3 = expect_forward!(nodes[1]);
5694                 assert_eq!(payment_event_3.msgs.len(), 2);
5695                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]).unwrap();
5696                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]).unwrap();
5697
5698                 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
5699                 expect_pending_htlcs_forwardable!(nodes[2]);
5700
5701                 let events = nodes[2].node.get_and_clear_pending_events();
5702                 assert_eq!(events.len(), 2);
5703                 match events[0] {
5704                         Event::PaymentReceived { ref payment_hash, amt } => {
5705                                 assert_eq!(our_payment_hash_21, *payment_hash);
5706                                 assert_eq!(recv_value_21, amt);
5707                         },
5708                         _ => panic!("Unexpected event"),
5709                 }
5710                 match events[1] {
5711                         Event::PaymentReceived { ref payment_hash, amt } => {
5712                                 assert_eq!(our_payment_hash_22, *payment_hash);
5713                                 assert_eq!(recv_value_22, amt);
5714                         },
5715                         _ => panic!("Unexpected event"),
5716                 }
5717
5718                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
5719                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
5720                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
5721
5722                 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);
5723                 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
5724                 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
5725                 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
5726
5727                 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
5728                 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
5729         }
5730
5731         #[test]
5732         fn channel_reserve_test() {
5733                 do_channel_reserve_test(false);
5734                 do_channel_reserve_test(true);
5735         }
5736
5737         #[test]
5738         fn channel_monitor_network_test() {
5739                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5740                 // tests that ChannelMonitor is able to recover from various states.
5741                 let nodes = create_network(5);
5742
5743                 // Create some initial channels
5744                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5745                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5746                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5747                 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5748
5749                 // Rebalance the network a bit by relaying one payment through all the channels...
5750                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5751                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5752                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5753                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5754
5755                 // Simple case with no pending HTLCs:
5756                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
5757                 {
5758                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
5759                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5760                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5761                         test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
5762                 }
5763                 get_announce_close_broadcast_events(&nodes, 0, 1);
5764                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5765                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5766
5767                 // One pending HTLC is discarded by the force-close:
5768                 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
5769
5770                 // Simple case of one pending HTLC to HTLC-Timeout
5771                 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
5772                 {
5773                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
5774                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5775                         nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5776                         test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
5777                 }
5778                 get_announce_close_broadcast_events(&nodes, 1, 2);
5779                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5780                 assert_eq!(nodes[2].node.list_channels().len(), 1);
5781
5782                 macro_rules! claim_funds {
5783                         ($node: expr, $prev_node: expr, $preimage: expr) => {
5784                                 {
5785                                         assert!($node.node.claim_funds($preimage));
5786                                         check_added_monitors!($node, 1);
5787
5788                                         let events = $node.node.get_and_clear_pending_msg_events();
5789                                         assert_eq!(events.len(), 1);
5790                                         match events[0] {
5791                                                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
5792                                                         assert!(update_add_htlcs.is_empty());
5793                                                         assert!(update_fail_htlcs.is_empty());
5794                                                         assert_eq!(*node_id, $prev_node.node.get_our_node_id());
5795                                                 },
5796                                                 _ => panic!("Unexpected event"),
5797                                         };
5798                                 }
5799                         }
5800                 }
5801
5802                 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
5803                 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
5804                 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
5805                 {
5806                         let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
5807
5808                         // Claim the payment on nodes[3], giving it knowledge of the preimage
5809                         claim_funds!(nodes[3], nodes[2], payment_preimage_1);
5810
5811                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5812                         nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
5813
5814                         check_preimage_claim(&nodes[3], &node_txn);
5815                 }
5816                 get_announce_close_broadcast_events(&nodes, 2, 3);
5817                 assert_eq!(nodes[2].node.list_channels().len(), 0);
5818                 assert_eq!(nodes[3].node.list_channels().len(), 1);
5819
5820                 { // Cheat and reset nodes[4]'s height to 1
5821                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5822                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![] }, 1);
5823                 }
5824
5825                 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
5826                 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
5827                 // One pending HTLC to time out:
5828                 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
5829                 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
5830                 // buffer space).
5831
5832                 {
5833                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5834                         nodes[3].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5835                         for i in 3..TEST_FINAL_CLTV + 2 + HTLC_FAIL_TIMEOUT_BLOCKS + 1 {
5836                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5837                                 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5838                         }
5839
5840                         let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
5841
5842                         // Claim the payment on nodes[4], giving it knowledge of the preimage
5843                         claim_funds!(nodes[4], nodes[3], payment_preimage_2);
5844
5845                         header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5846                         nodes[4].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5847                         for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
5848                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5849                                 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5850                         }
5851
5852                         test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
5853
5854                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5855                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
5856
5857                         check_preimage_claim(&nodes[4], &node_txn);
5858                 }
5859                 get_announce_close_broadcast_events(&nodes, 3, 4);
5860                 assert_eq!(nodes[3].node.list_channels().len(), 0);
5861                 assert_eq!(nodes[4].node.list_channels().len(), 0);
5862         }
5863
5864         #[test]
5865         fn test_justice_tx() {
5866                 // Test justice txn built on revoked HTLC-Success tx, against both sides
5867
5868                 let nodes = create_network(2);
5869                 // Create some new channels:
5870                 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
5871
5872                 // A pending HTLC which will be revoked:
5873                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5874                 // Get the will-be-revoked local txn from nodes[0]
5875                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5876                 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
5877                 assert_eq!(revoked_local_txn[0].input.len(), 1);
5878                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
5879                 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
5880                 assert_eq!(revoked_local_txn[1].input.len(), 1);
5881                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
5882                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
5883                 // Revoke the old state
5884                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
5885
5886                 {
5887                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5888                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5889                         {
5890                                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5891                                 assert_eq!(node_txn.len(), 3);
5892                                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5893                                 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
5894
5895                                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5896                                 node_txn.swap_remove(0);
5897                         }
5898                         test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
5899
5900                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5901                         let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
5902                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5903                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5904                         test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
5905                 }
5906                 get_announce_close_broadcast_events(&nodes, 0, 1);
5907
5908                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5909                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5910
5911                 // We test justice_tx build by A on B's revoked HTLC-Success tx
5912                 // Create some new channels:
5913                 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
5914
5915                 // A pending HTLC which will be revoked:
5916                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5917                 // Get the will-be-revoked local txn from B
5918                 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5919                 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
5920                 assert_eq!(revoked_local_txn[0].input.len(), 1);
5921                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
5922                 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
5923                 // Revoke the old state
5924                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
5925                 {
5926                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5927                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5928                         {
5929                                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5930                                 assert_eq!(node_txn.len(), 3);
5931                                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5932                                 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
5933
5934                                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5935                                 node_txn.swap_remove(0);
5936                         }
5937                         test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
5938
5939                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5940                         let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
5941                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5942                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5943                         test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone());
5944                 }
5945                 get_announce_close_broadcast_events(&nodes, 0, 1);
5946                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5947                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5948         }
5949
5950         #[test]
5951         fn revoked_output_claim() {
5952                 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
5953                 // transaction is broadcast by its counterparty
5954                 let nodes = create_network(2);
5955                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5956                 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
5957                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5958                 assert_eq!(revoked_local_txn.len(), 1);
5959                 // Only output is the full channel value back to nodes[0]:
5960                 assert_eq!(revoked_local_txn[0].output.len(), 1);
5961                 // Send a payment through, updating everyone's latest commitment txn
5962                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
5963
5964                 // Inform nodes[1] that nodes[0] broadcast a stale tx
5965                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5966                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5967                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5968                 assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
5969
5970                 assert_eq!(node_txn[0], node_txn[2]);
5971
5972                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5973                 check_spends!(node_txn[1], chan_1.3.clone());
5974
5975                 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
5976                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5977                 get_announce_close_broadcast_events(&nodes, 0, 1);
5978         }
5979
5980         #[test]
5981         fn claim_htlc_outputs_shared_tx() {
5982                 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
5983                 let nodes = create_network(2);
5984
5985                 // Create some new channel:
5986                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5987
5988                 // Rebalance the network to generate htlc in the two directions
5989                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5990                 // 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
5991                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5992                 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
5993
5994                 // Get the will-be-revoked local txn from node[0]
5995                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5996                 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
5997                 assert_eq!(revoked_local_txn[0].input.len(), 1);
5998                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5999                 assert_eq!(revoked_local_txn[1].input.len(), 1);
6000                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
6001                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
6002                 check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
6003
6004                 //Revoke the old state
6005                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6006
6007                 {
6008                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6009                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6010                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6011
6012                         let events = nodes[1].node.get_and_clear_pending_events();
6013                         assert_eq!(events.len(), 1);
6014                         match events[0] {
6015                                 Event::PaymentFailed { payment_hash, .. } => {
6016                                         assert_eq!(payment_hash, payment_hash_2);
6017                                 },
6018                                 _ => panic!("Unexpected event"),
6019                         }
6020
6021                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6022                         assert_eq!(node_txn.len(), 4);
6023
6024                         assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
6025                         check_spends!(node_txn[0], revoked_local_txn[0].clone());
6026
6027                         assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
6028
6029                         let mut witness_lens = BTreeSet::new();
6030                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6031                         witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
6032                         witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
6033                         assert_eq!(witness_lens.len(), 3);
6034                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6035                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
6036                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
6037
6038                         // Next nodes[1] broadcasts its current local tx state:
6039                         assert_eq!(node_txn[1].input.len(), 1);
6040                         assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
6041
6042                         assert_eq!(node_txn[2].input.len(), 1);
6043                         let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
6044                         assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
6045                         assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
6046                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6047                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
6048                 }
6049                 get_announce_close_broadcast_events(&nodes, 0, 1);
6050                 assert_eq!(nodes[0].node.list_channels().len(), 0);
6051                 assert_eq!(nodes[1].node.list_channels().len(), 0);
6052         }
6053
6054         #[test]
6055         fn claim_htlc_outputs_single_tx() {
6056                 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
6057                 let nodes = create_network(2);
6058
6059                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6060
6061                 // Rebalance the network to generate htlc in the two directions
6062                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6063                 // 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
6064                 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
6065                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6066                 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6067
6068                 // Get the will-be-revoked local txn from node[0]
6069                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6070
6071                 //Revoke the old state
6072                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6073
6074                 {
6075                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6076                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6077                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6078
6079                         let events = nodes[1].node.get_and_clear_pending_events();
6080                         assert_eq!(events.len(), 1);
6081                         match events[0] {
6082                                 Event::PaymentFailed { payment_hash, .. } => {
6083                                         assert_eq!(payment_hash, payment_hash_2);
6084                                 },
6085                                 _ => panic!("Unexpected event"),
6086                         }
6087
6088                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6089                         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)
6090
6091                         assert_eq!(node_txn[0], node_txn[7]);
6092                         assert_eq!(node_txn[1], node_txn[8]);
6093                         assert_eq!(node_txn[2], node_txn[9]);
6094                         assert_eq!(node_txn[3], node_txn[10]);
6095                         assert_eq!(node_txn[4], node_txn[11]);
6096                         assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcated by ChannelManger
6097                         assert_eq!(node_txn[4], node_txn[6]);
6098
6099                         assert_eq!(node_txn[0].input.len(), 1);
6100                         assert_eq!(node_txn[1].input.len(), 1);
6101                         assert_eq!(node_txn[2].input.len(), 1);
6102
6103                         let mut revoked_tx_map = HashMap::new();
6104                         revoked_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
6105                         node_txn[0].verify(&revoked_tx_map).unwrap();
6106                         node_txn[1].verify(&revoked_tx_map).unwrap();
6107                         node_txn[2].verify(&revoked_tx_map).unwrap();
6108
6109                         let mut witness_lens = BTreeSet::new();
6110                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6111                         witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
6112                         witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
6113                         assert_eq!(witness_lens.len(), 3);
6114                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6115                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
6116                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
6117
6118                         assert_eq!(node_txn[3].input.len(), 1);
6119                         check_spends!(node_txn[3], chan_1.3.clone());
6120
6121                         assert_eq!(node_txn[4].input.len(), 1);
6122                         let witness_script = node_txn[4].input[0].witness.last().unwrap();
6123                         assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
6124                         assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
6125                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6126                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
6127                 }
6128                 get_announce_close_broadcast_events(&nodes, 0, 1);
6129                 assert_eq!(nodes[0].node.list_channels().len(), 0);
6130                 assert_eq!(nodes[1].node.list_channels().len(), 0);
6131         }
6132
6133         #[test]
6134         fn test_htlc_on_chain_success() {
6135                 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
6136                 // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
6137                 // broadcasting the right event to other nodes in payment path.
6138                 // A --------------------> B ----------------------> C (preimage)
6139                 // First, C should claim the HTLC output via HTLC-Success when its own latest local
6140                 // commitment transaction was broadcast.
6141                 // Then, B should learn the preimage from said transactions, attempting to claim backwards
6142                 // towards B.
6143                 // B should be able to claim via preimage if A then broadcasts its local tx.
6144                 // Finally, when A sees B's latest local commitment transaction it should be able to claim
6145                 // the HTLC output via the preimage it learned (which, once confirmed should generate a
6146                 // PaymentSent event).
6147
6148                 let nodes = create_network(3);
6149
6150                 // Create some initial channels
6151                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6152                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6153
6154                 // Rebalance the network a bit by relaying one payment through all the channels...
6155                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6156                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6157
6158                 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
6159                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6160
6161                 // Broadcast legit commitment tx from C on B's chain
6162                 // Broadcast HTLC Success transation by C on received output from C's commitment tx on B's chain
6163                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6164                 assert_eq!(commitment_tx.len(), 1);
6165                 check_spends!(commitment_tx[0], chan_2.3.clone());
6166                 nodes[2].node.claim_funds(our_payment_preimage);
6167                 check_added_monitors!(nodes[2], 1);
6168                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6169                 assert!(updates.update_add_htlcs.is_empty());
6170                 assert!(updates.update_fail_htlcs.is_empty());
6171                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6172                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
6173
6174                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6175                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6176                 assert_eq!(events.len(), 1);
6177                 match events[0] {
6178                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6179                         _ => panic!("Unexpected event"),
6180                 }
6181                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
6182                 assert_eq!(node_txn.len(), 3);
6183                 assert_eq!(node_txn[1], commitment_tx[0]);
6184                 assert_eq!(node_txn[0], node_txn[2]);
6185                 check_spends!(node_txn[0], commitment_tx[0].clone());
6186                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6187                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6188                 assert_eq!(node_txn[0].lock_time, 0);
6189
6190                 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
6191                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: node_txn}, 1);
6192                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6193                 {
6194                         let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
6195                         assert_eq!(added_monitors.len(), 1);
6196                         assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
6197                         added_monitors.clear();
6198                 }
6199                 assert_eq!(events.len(), 2);
6200                 match events[0] {
6201                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6202                         _ => panic!("Unexpected event"),
6203                 }
6204                 match events[1] {
6205                         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, .. } } => {
6206                                 assert!(update_add_htlcs.is_empty());
6207                                 assert!(update_fail_htlcs.is_empty());
6208                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6209                                 assert!(update_fail_malformed_htlcs.is_empty());
6210                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6211                         },
6212                         _ => panic!("Unexpected event"),
6213                 };
6214                 {
6215                         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
6216                         // commitment transaction with a corresponding HTLC-Timeout transaction, as well as a
6217                         // timeout-claim of the output that nodes[2] just claimed via success.
6218                         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)
6219                         assert_eq!(node_txn.len(), 4);
6220                         assert_eq!(node_txn[0], node_txn[3]);
6221                         check_spends!(node_txn[0], commitment_tx[0].clone());
6222                         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6223                         assert_ne!(node_txn[0].lock_time, 0);
6224                         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
6225                         check_spends!(node_txn[1], chan_2.3.clone());
6226                         check_spends!(node_txn[2], node_txn[1].clone());
6227                         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6228                         assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6229                         assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6230                         assert_ne!(node_txn[2].lock_time, 0);
6231                         node_txn.clear();
6232                 }
6233
6234                 // Broadcast legit commitment tx from A on B's chain
6235                 // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
6236                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6237                 check_spends!(commitment_tx[0], chan_1.3.clone());
6238                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6239                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6240                 assert_eq!(events.len(), 1);
6241                 match events[0] {
6242                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6243                         _ => panic!("Unexpected event"),
6244                 }
6245                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 1 (HTLC-Success) * 2 (block-rescan)
6246                 assert_eq!(node_txn.len(), 3);
6247                 assert_eq!(node_txn[0], node_txn[2]);
6248                 check_spends!(node_txn[0], commitment_tx[0].clone());
6249                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6250                 assert_eq!(node_txn[0].lock_time, 0);
6251                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
6252                 check_spends!(node_txn[1], chan_1.3.clone());
6253                 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6254                 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
6255                 // we already checked the same situation with A.
6256
6257                 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
6258                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
6259                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6260                 assert_eq!(events.len(), 1);
6261                 match events[0] {
6262                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6263                         _ => panic!("Unexpected event"),
6264                 }
6265                 let events = nodes[0].node.get_and_clear_pending_events();
6266                 assert_eq!(events.len(), 1);
6267                 match events[0] {
6268                         Event::PaymentSent { payment_preimage } => {
6269                                 assert_eq!(payment_preimage, our_payment_preimage);
6270                         },
6271                         _ => panic!("Unexpected event"),
6272                 }
6273                 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)
6274                 assert_eq!(node_txn.len(), 4);
6275                 assert_eq!(node_txn[0], node_txn[3]);
6276                 check_spends!(node_txn[0], commitment_tx[0].clone());
6277                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6278                 assert_ne!(node_txn[0].lock_time, 0);
6279                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6280                 check_spends!(node_txn[1], chan_1.3.clone());
6281                 check_spends!(node_txn[2], node_txn[1].clone());
6282                 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6283                 assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6284                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6285                 assert_ne!(node_txn[2].lock_time, 0);
6286         }
6287
6288         #[test]
6289         fn test_htlc_on_chain_timeout() {
6290                 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
6291                 // ChainWatchInterface and timeout the HTLC  bacward accordingly. So here we test that ChannelManager is
6292                 // broadcasting the right event to other nodes in payment path.
6293                 // A ------------------> B ----------------------> C (timeout)
6294                 //    B's commitment tx                 C's commitment tx
6295                 //            \                                  \
6296                 //         B's HTLC timeout tx               B's timeout tx
6297
6298                 let nodes = create_network(3);
6299
6300                 // Create some intial channels
6301                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6302                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6303
6304                 // Rebalance the network a bit by relaying one payment thorugh all the channels...
6305                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6306                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6307
6308                 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
6309                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6310
6311                 // Brodacast legit commitment tx from C on B's chain
6312                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6313                 check_spends!(commitment_tx[0], chan_2.3.clone());
6314                 nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
6315                 {
6316                         let mut added_monitors = nodes[2].chan_monitor.added_monitors.lock().unwrap();
6317                         assert_eq!(added_monitors.len(), 1);
6318                         added_monitors.clear();
6319                 }
6320                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6321                 assert_eq!(events.len(), 1);
6322                 match events[0] {
6323                         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, .. } } => {
6324                                 assert!(update_add_htlcs.is_empty());
6325                                 assert!(!update_fail_htlcs.is_empty());
6326                                 assert!(update_fulfill_htlcs.is_empty());
6327                                 assert!(update_fail_malformed_htlcs.is_empty());
6328                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
6329                         },
6330                         _ => panic!("Unexpected event"),
6331                 };
6332                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6333                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6334                 assert_eq!(events.len(), 1);
6335                 match events[0] {
6336                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6337                         _ => panic!("Unexpected event"),
6338                 }
6339                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
6340                 assert_eq!(node_txn.len(), 1);
6341                 check_spends!(node_txn[0], chan_2.3.clone());
6342                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
6343
6344                 // Broadcast timeout transaction by B on received output fron C's commitment tx on B's chain
6345                 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
6346                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6347                 let timeout_tx;
6348                 {
6349                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6350                         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)
6351                         assert_eq!(node_txn[0], node_txn[5]);
6352                         assert_eq!(node_txn[1], node_txn[6]);
6353                         assert_eq!(node_txn[2], node_txn[7]);
6354                         check_spends!(node_txn[0], commitment_tx[0].clone());
6355                         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6356                         check_spends!(node_txn[1], chan_2.3.clone());
6357                         check_spends!(node_txn[2], node_txn[1].clone());
6358                         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6359                         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6360                         check_spends!(node_txn[3], chan_2.3.clone());
6361                         check_spends!(node_txn[4], node_txn[3].clone());
6362                         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
6363                         assert_eq!(node_txn[4].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6364                         timeout_tx = node_txn[0].clone();
6365                         node_txn.clear();
6366                 }
6367
6368                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![timeout_tx]}, 1);
6369                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6370                 check_added_monitors!(nodes[1], 1);
6371                 assert_eq!(events.len(), 2);
6372                 match events[0] {
6373                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6374                         _ => panic!("Unexpected event"),
6375                 }
6376                 match events[1] {
6377                         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, .. } } => {
6378                                 assert!(update_add_htlcs.is_empty());
6379                                 assert!(!update_fail_htlcs.is_empty());
6380                                 assert!(update_fulfill_htlcs.is_empty());
6381                                 assert!(update_fail_malformed_htlcs.is_empty());
6382                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6383                         },
6384                         _ => panic!("Unexpected event"),
6385                 };
6386                 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
6387                 assert_eq!(node_txn.len(), 0);
6388
6389                 // Broadcast legit commitment tx from B on A's chain
6390                 let commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6391                 check_spends!(commitment_tx[0], chan_1.3.clone());
6392
6393                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6394                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6395                 assert_eq!(events.len(), 1);
6396                 match events[0] {
6397                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6398                         _ => panic!("Unexpected event"),
6399                 }
6400                 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
6401                 assert_eq!(node_txn.len(), 4);
6402                 assert_eq!(node_txn[0], node_txn[3]);
6403                 check_spends!(node_txn[0], commitment_tx[0].clone());
6404                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6405                 check_spends!(node_txn[1], chan_1.3.clone());
6406                 check_spends!(node_txn[2], node_txn[1].clone());
6407                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6408                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6409         }
6410
6411         #[test]
6412         fn test_simple_commitment_revoked_fail_backward() {
6413                 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
6414                 // and fail backward accordingly.
6415
6416                 let nodes = create_network(3);
6417
6418                 // Create some initial channels
6419                 create_announced_chan_between_nodes(&nodes, 0, 1);
6420                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6421
6422                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6423                 // Get the will-be-revoked local txn from nodes[2]
6424                 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6425                 // Revoke the old state
6426                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6427
6428                 route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6429
6430                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6431                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6432                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6433                 check_added_monitors!(nodes[1], 1);
6434                 assert_eq!(events.len(), 2);
6435                 match events[0] {
6436                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6437                         _ => panic!("Unexpected event"),
6438                 }
6439                 match events[1] {
6440                         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, .. } } => {
6441                                 assert!(update_add_htlcs.is_empty());
6442                                 assert_eq!(update_fail_htlcs.len(), 1);
6443                                 assert!(update_fulfill_htlcs.is_empty());
6444                                 assert!(update_fail_malformed_htlcs.is_empty());
6445                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6446
6447                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6448                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6449
6450                                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6451                                 assert_eq!(events.len(), 1);
6452                                 match events[0] {
6453                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6454                                         _ => panic!("Unexpected event"),
6455                                 }
6456                                 let events = nodes[0].node.get_and_clear_pending_events();
6457                                 assert_eq!(events.len(), 1);
6458                                 match events[0] {
6459                                         Event::PaymentFailed { .. } => {},
6460                                         _ => panic!("Unexpected event"),
6461                                 }
6462                         },
6463                         _ => panic!("Unexpected event"),
6464                 }
6465         }
6466
6467         fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool) {
6468                 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
6469                 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
6470                 // commitment transaction anymore.
6471                 // To do this, we have the peer which will broadcast a revoked commitment transaction send
6472                 // a number of update_fail/commitment_signed updates without ever sending the RAA in
6473                 // response to our commitment_signed. This is somewhat misbehavior-y, though not
6474                 // technically disallowed and we should probably handle it reasonably.
6475                 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
6476                 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
6477                 // transactions:
6478                 // * Once we move it out of our holding cell/add it, we will immediately include it in a
6479                 //   commitment_signed (implying it will be in the latest remote commitment transaction).
6480                 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
6481                 //   and once they revoke the previous commitment transaction (allowing us to send a new
6482                 //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
6483                 let mut nodes = create_network(3);
6484
6485                 // Create some initial channels
6486                 create_announced_chan_between_nodes(&nodes, 0, 1);
6487                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6488
6489                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6490                 // Get the will-be-revoked local txn from nodes[2]
6491                 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6492                 // Revoke the old state
6493                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6494
6495                 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6496                 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6497                 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6498
6499                 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, 0));
6500                 check_added_monitors!(nodes[2], 1);
6501                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6502                 assert!(updates.update_add_htlcs.is_empty());
6503                 assert!(updates.update_fulfill_htlcs.is_empty());
6504                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6505                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6506                 assert!(updates.update_fee.is_none());
6507                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6508                 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
6509                 // Drop the last RAA from 3 -> 2
6510
6511                 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, 0));
6512                 check_added_monitors!(nodes[2], 1);
6513                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6514                 assert!(updates.update_add_htlcs.is_empty());
6515                 assert!(updates.update_fulfill_htlcs.is_empty());
6516                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6517                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6518                 assert!(updates.update_fee.is_none());
6519                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6520                 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6521                 check_added_monitors!(nodes[1], 1);
6522                 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
6523                 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6524                 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6525                 check_added_monitors!(nodes[2], 1);
6526
6527                 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, 0));
6528                 check_added_monitors!(nodes[2], 1);
6529                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6530                 assert!(updates.update_add_htlcs.is_empty());
6531                 assert!(updates.update_fulfill_htlcs.is_empty());
6532                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6533                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6534                 assert!(updates.update_fee.is_none());
6535                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6536                 // At this point first_payment_hash has dropped out of the latest two commitment
6537                 // transactions that nodes[1] is tracking...
6538                 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6539                 check_added_monitors!(nodes[1], 1);
6540                 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
6541                 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6542                 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6543                 check_added_monitors!(nodes[2], 1);
6544
6545                 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
6546                 // on nodes[2]'s RAA.
6547                 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
6548                 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6549                 nodes[1].node.send_payment(route, fourth_payment_hash).unwrap();
6550                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
6551                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6552                 check_added_monitors!(nodes[1], 0);
6553
6554                 if deliver_bs_raa {
6555                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa).unwrap();
6556                         // One monitor for the new revocation preimage, one as we generate a commitment for
6557                         // nodes[0] to fail first_payment_hash backwards.
6558                         check_added_monitors!(nodes[1], 2);
6559                 }
6560
6561                 let mut failed_htlcs = HashSet::new();
6562                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6563
6564                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6565                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6566
6567                 let events = nodes[1].node.get_and_clear_pending_events();
6568                 assert_eq!(events.len(), 1);
6569                 match events[0] {
6570                         Event::PaymentFailed { ref payment_hash, .. } => {
6571                                 assert_eq!(*payment_hash, fourth_payment_hash);
6572                         },
6573                         _ => panic!("Unexpected event"),
6574                 }
6575
6576                 if !deliver_bs_raa {
6577                         // If we delivered the RAA already then we already failed first_payment_hash backwards.
6578                         check_added_monitors!(nodes[1], 1);
6579                 }
6580
6581                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6582                 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
6583                 match events[if deliver_bs_raa { 2 } else { 0 }] {
6584                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6585                         _ => panic!("Unexpected event"),
6586                 }
6587                 if deliver_bs_raa {
6588                         match events[0] {
6589                                 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, .. } } => {
6590                                         assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
6591                                         assert_eq!(update_add_htlcs.len(), 1);
6592                                         assert!(update_fulfill_htlcs.is_empty());
6593                                         assert!(update_fail_htlcs.is_empty());
6594                                         assert!(update_fail_malformed_htlcs.is_empty());
6595                                 },
6596                                 _ => panic!("Unexpected event"),
6597                         }
6598                 }
6599                 // Due to the way backwards-failing occurs we do the updates in two steps.
6600                 let updates = match events[1] {
6601                         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, .. } } => {
6602                                 assert!(update_add_htlcs.is_empty());
6603                                 assert_eq!(update_fail_htlcs.len(), 1);
6604                                 assert!(update_fulfill_htlcs.is_empty());
6605                                 assert!(update_fail_malformed_htlcs.is_empty());
6606                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6607
6608                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6609                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
6610                                 check_added_monitors!(nodes[0], 1);
6611                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6612                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6613                                 check_added_monitors!(nodes[1], 1);
6614                                 let bs_second_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6615                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
6616                                 check_added_monitors!(nodes[1], 1);
6617                                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6618                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6619                                 check_added_monitors!(nodes[0], 1);
6620
6621                                 if !deliver_bs_raa {
6622                                         // If we delievered B's RAA we got an unknown preimage error, not something
6623                                         // that we should update our routing table for.
6624                                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6625                                         assert_eq!(events.len(), 1);
6626                                         match events[0] {
6627                                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6628                                                 _ => panic!("Unexpected event"),
6629                                         }
6630                                 }
6631                                 let events = nodes[0].node.get_and_clear_pending_events();
6632                                 assert_eq!(events.len(), 1);
6633                                 match events[0] {
6634                                         Event::PaymentFailed { ref payment_hash, .. } => {
6635                                                 assert!(failed_htlcs.insert(payment_hash.0));
6636                                         },
6637                                         _ => panic!("Unexpected event"),
6638                                 }
6639
6640                                 bs_second_update
6641                         },
6642                         _ => panic!("Unexpected event"),
6643                 };
6644
6645                 assert!(updates.update_add_htlcs.is_empty());
6646                 assert_eq!(updates.update_fail_htlcs.len(), 2);
6647                 assert!(updates.update_fulfill_htlcs.is_empty());
6648                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6649                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6650                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[1]).unwrap();
6651                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6652
6653                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6654                 assert_eq!(events.len(), 2);
6655                 for event in events {
6656                         match event {
6657                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6658                                 _ => panic!("Unexpected event"),
6659                         }
6660                 }
6661
6662                 let events = nodes[0].node.get_and_clear_pending_events();
6663                 assert_eq!(events.len(), 2);
6664                 match events[0] {
6665                         Event::PaymentFailed { ref payment_hash, .. } => {
6666                                 assert!(failed_htlcs.insert(payment_hash.0));
6667                         },
6668                         _ => panic!("Unexpected event"),
6669                 }
6670                 match events[1] {
6671                         Event::PaymentFailed { ref payment_hash, .. } => {
6672                                 assert!(failed_htlcs.insert(payment_hash.0));
6673                         },
6674                         _ => panic!("Unexpected event"),
6675                 }
6676
6677                 assert!(failed_htlcs.contains(&first_payment_hash.0));
6678                 assert!(failed_htlcs.contains(&second_payment_hash.0));
6679                 assert!(failed_htlcs.contains(&third_payment_hash.0));
6680         }
6681
6682         #[test]
6683         fn test_commitment_revoked_fail_backward_exhaustive() {
6684                 do_test_commitment_revoked_fail_backward_exhaustive(false);
6685                 do_test_commitment_revoked_fail_backward_exhaustive(true);
6686         }
6687
6688         #[test]
6689         fn test_htlc_ignore_latest_remote_commitment() {
6690                 // Test that HTLC transactions spending the latest remote commitment transaction are simply
6691                 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
6692                 let nodes = create_network(2);
6693                 create_announced_chan_between_nodes(&nodes, 0, 1);
6694
6695                 route_payment(&nodes[0], &[&nodes[1]], 10000000);
6696                 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
6697                 {
6698                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6699                         assert_eq!(events.len(), 1);
6700                         match events[0] {
6701                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6702                                         assert_eq!(flags & 0b10, 0b10);
6703                                 },
6704                                 _ => panic!("Unexpected event"),
6705                         }
6706                 }
6707
6708                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6709                 assert_eq!(node_txn.len(), 2);
6710
6711                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6712                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6713
6714                 {
6715                         let events = nodes[1].node.get_and_clear_pending_msg_events();
6716                         assert_eq!(events.len(), 1);
6717                         match events[0] {
6718                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6719                                         assert_eq!(flags & 0b10, 0b10);
6720                                 },
6721                                 _ => panic!("Unexpected event"),
6722                         }
6723                 }
6724
6725                 // Duplicate the block_connected call since this may happen due to other listeners
6726                 // registering new transactions
6727                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6728         }
6729
6730         #[test]
6731         fn test_force_close_fail_back() {
6732                 // Check which HTLCs are failed-backwards on channel force-closure
6733                 let mut nodes = create_network(3);
6734                 create_announced_chan_between_nodes(&nodes, 0, 1);
6735                 create_announced_chan_between_nodes(&nodes, 1, 2);
6736
6737                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
6738
6739                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6740
6741                 let mut payment_event = {
6742                         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6743                         check_added_monitors!(nodes[0], 1);
6744
6745                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6746                         assert_eq!(events.len(), 1);
6747                         SendEvent::from_event(events.remove(0))
6748                 };
6749
6750                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6751                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6752
6753                 let events_1 = nodes[1].node.get_and_clear_pending_events();
6754                 assert_eq!(events_1.len(), 1);
6755                 match events_1[0] {
6756                         Event::PendingHTLCsForwardable { .. } => { },
6757                         _ => panic!("Unexpected event"),
6758                 };
6759
6760                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
6761                 nodes[1].node.process_pending_htlc_forwards();
6762
6763                 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6764                 assert_eq!(events_2.len(), 1);
6765                 payment_event = SendEvent::from_event(events_2.remove(0));
6766                 assert_eq!(payment_event.msgs.len(), 1);
6767
6768                 check_added_monitors!(nodes[1], 1);
6769                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6770                 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
6771                 check_added_monitors!(nodes[2], 1);
6772                 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6773
6774                 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
6775                 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
6776                 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
6777
6778                 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
6779                 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6780                 assert_eq!(events_3.len(), 1);
6781                 match events_3[0] {
6782                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6783                                 assert_eq!(flags & 0b10, 0b10);
6784                         },
6785                         _ => panic!("Unexpected event"),
6786                 }
6787
6788                 let tx = {
6789                         let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6790                         // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
6791                         // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
6792                         // back to nodes[1] upon timeout otherwise.
6793                         assert_eq!(node_txn.len(), 1);
6794                         node_txn.remove(0)
6795                 };
6796
6797                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6798                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6799
6800                 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6801                 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
6802                 assert_eq!(events_4.len(), 1);
6803                 match events_4[0] {
6804                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6805                                 assert_eq!(flags & 0b10, 0b10);
6806                         },
6807                         _ => panic!("Unexpected event"),
6808                 }
6809
6810                 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
6811                 {
6812                         let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
6813                         monitors.get_mut(&OutPoint::new(Sha256dHash::from(&payment_event.commitment_msg.channel_id[..]), 0)).unwrap()
6814                                 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
6815                 }
6816                 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6817                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6818                 assert_eq!(node_txn.len(), 1);
6819                 assert_eq!(node_txn[0].input.len(), 1);
6820                 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
6821                 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
6822                 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
6823
6824                 check_spends!(node_txn[0], tx);
6825         }
6826
6827         #[test]
6828         fn test_unconf_chan() {
6829                 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
6830                 let nodes = create_network(2);
6831                 create_announced_chan_between_nodes(&nodes, 0, 1);
6832
6833                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6834                 assert_eq!(channel_state.by_id.len(), 1);
6835                 assert_eq!(channel_state.short_to_id.len(), 1);
6836                 mem::drop(channel_state);
6837
6838                 let mut headers = Vec::new();
6839                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6840                 headers.push(header.clone());
6841                 for _i in 2..100 {
6842                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6843                         headers.push(header.clone());
6844                 }
6845                 while !headers.is_empty() {
6846                         nodes[0].node.block_disconnected(&headers.pop().unwrap());
6847                 }
6848                 {
6849                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6850                         assert_eq!(events.len(), 1);
6851                         match events[0] {
6852                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6853                                         assert_eq!(flags & 0b10, 0b10);
6854                                 },
6855                                 _ => panic!("Unexpected event"),
6856                         }
6857                 }
6858                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6859                 assert_eq!(channel_state.by_id.len(), 0);
6860                 assert_eq!(channel_state.short_to_id.len(), 0);
6861         }
6862
6863         macro_rules! get_chan_reestablish_msgs {
6864                 ($src_node: expr, $dst_node: expr) => {
6865                         {
6866                                 let mut res = Vec::with_capacity(1);
6867                                 for msg in $src_node.node.get_and_clear_pending_msg_events() {
6868                                         if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
6869                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6870                                                 res.push(msg.clone());
6871                                         } else {
6872                                                 panic!("Unexpected event")
6873                                         }
6874                                 }
6875                                 res
6876                         }
6877                 }
6878         }
6879
6880         macro_rules! handle_chan_reestablish_msgs {
6881                 ($src_node: expr, $dst_node: expr) => {
6882                         {
6883                                 let msg_events = $src_node.node.get_and_clear_pending_msg_events();
6884                                 let mut idx = 0;
6885                                 let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
6886                                         idx += 1;
6887                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6888                                         Some(msg.clone())
6889                                 } else {
6890                                         None
6891                                 };
6892
6893                                 let mut revoke_and_ack = None;
6894                                 let mut commitment_update = None;
6895                                 let order = if let Some(ev) = msg_events.get(idx) {
6896                                         idx += 1;
6897                                         match ev {
6898                                                 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6899                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6900                                                         revoke_and_ack = Some(msg.clone());
6901                                                         RAACommitmentOrder::RevokeAndACKFirst
6902                                                 },
6903                                                 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6904                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6905                                                         commitment_update = Some(updates.clone());
6906                                                         RAACommitmentOrder::CommitmentFirst
6907                                                 },
6908                                                 _ => panic!("Unexpected event"),
6909                                         }
6910                                 } else {
6911                                         RAACommitmentOrder::CommitmentFirst
6912                                 };
6913
6914                                 if let Some(ev) = msg_events.get(idx) {
6915                                         match ev {
6916                                                 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6917                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6918                                                         assert!(revoke_and_ack.is_none());
6919                                                         revoke_and_ack = Some(msg.clone());
6920                                                 },
6921                                                 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6922                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6923                                                         assert!(commitment_update.is_none());
6924                                                         commitment_update = Some(updates.clone());
6925                                                 },
6926                                                 _ => panic!("Unexpected event"),
6927                                         }
6928                                 }
6929
6930                                 (funding_locked, revoke_and_ack, commitment_update, order)
6931                         }
6932                 }
6933         }
6934
6935         /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
6936         /// for claims/fails they are separated out.
6937         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)) {
6938                 node_a.node.peer_connected(&node_b.node.get_our_node_id());
6939                 let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
6940                 node_b.node.peer_connected(&node_a.node.get_our_node_id());
6941                 let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
6942
6943                 if send_funding_locked.0 {
6944                         // If a expects a funding_locked, it better not think it has received a revoke_and_ack
6945                         // from b
6946                         for reestablish in reestablish_1.iter() {
6947                                 assert_eq!(reestablish.next_remote_commitment_number, 0);
6948                         }
6949                 }
6950                 if send_funding_locked.1 {
6951                         // If b expects a funding_locked, it better not think it has received a revoke_and_ack
6952                         // from a
6953                         for reestablish in reestablish_2.iter() {
6954                                 assert_eq!(reestablish.next_remote_commitment_number, 0);
6955                         }
6956                 }
6957                 if send_funding_locked.0 || send_funding_locked.1 {
6958                         // If we expect any funding_locked's, both sides better have set
6959                         // next_local_commitment_number to 1
6960                         for reestablish in reestablish_1.iter() {
6961                                 assert_eq!(reestablish.next_local_commitment_number, 1);
6962                         }
6963                         for reestablish in reestablish_2.iter() {
6964                                 assert_eq!(reestablish.next_local_commitment_number, 1);
6965                         }
6966                 }
6967
6968                 let mut resp_1 = Vec::new();
6969                 for msg in reestablish_1 {
6970                         node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg).unwrap();
6971                         resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
6972                 }
6973                 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
6974                         check_added_monitors!(node_b, 1);
6975                 } else {
6976                         check_added_monitors!(node_b, 0);
6977                 }
6978
6979                 let mut resp_2 = Vec::new();
6980                 for msg in reestablish_2 {
6981                         node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg).unwrap();
6982                         resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
6983                 }
6984                 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
6985                         check_added_monitors!(node_a, 1);
6986                 } else {
6987                         check_added_monitors!(node_a, 0);
6988                 }
6989
6990                 // We dont yet support both needing updates, as that would require a different commitment dance:
6991                 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
6992                         (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
6993
6994                 for chan_msgs in resp_1.drain(..) {
6995                         if send_funding_locked.0 {
6996                                 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
6997                                 let announcement_event = node_a.node.get_and_clear_pending_msg_events();
6998                                 if !announcement_event.is_empty() {
6999                                         assert_eq!(announcement_event.len(), 1);
7000                                         if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
7001                                                 //TODO: Test announcement_sigs re-sending
7002                                         } else { panic!("Unexpected event!"); }
7003                                 }
7004                         } else {
7005                                 assert!(chan_msgs.0.is_none());
7006                         }
7007                         if pending_raa.0 {
7008                                 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
7009                                 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
7010                                 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
7011                                 check_added_monitors!(node_a, 1);
7012                         } else {
7013                                 assert!(chan_msgs.1.is_none());
7014                         }
7015                         if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
7016                                 let commitment_update = chan_msgs.2.unwrap();
7017                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
7018                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
7019                                 } else {
7020                                         assert!(commitment_update.update_add_htlcs.is_empty());
7021                                 }
7022                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
7023                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
7024                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
7025                                 for update_add in commitment_update.update_add_htlcs {
7026                                         node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add).unwrap();
7027                                 }
7028                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
7029                                         node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill).unwrap();
7030                                 }
7031                                 for update_fail in commitment_update.update_fail_htlcs {
7032                                         node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail).unwrap();
7033                                 }
7034
7035                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
7036                                         commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
7037                                 } else {
7038                                         node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
7039                                         check_added_monitors!(node_a, 1);
7040                                         let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
7041                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
7042                                         node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7043                                         assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
7044                                         check_added_monitors!(node_b, 1);
7045                                 }
7046                         } else {
7047                                 assert!(chan_msgs.2.is_none());
7048                         }
7049                 }
7050
7051                 for chan_msgs in resp_2.drain(..) {
7052                         if send_funding_locked.1 {
7053                                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
7054                                 let announcement_event = node_b.node.get_and_clear_pending_msg_events();
7055                                 if !announcement_event.is_empty() {
7056                                         assert_eq!(announcement_event.len(), 1);
7057                                         if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
7058                                                 //TODO: Test announcement_sigs re-sending
7059                                         } else { panic!("Unexpected event!"); }
7060                                 }
7061                         } else {
7062                                 assert!(chan_msgs.0.is_none());
7063                         }
7064                         if pending_raa.1 {
7065                                 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
7066                                 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
7067                                 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
7068                                 check_added_monitors!(node_b, 1);
7069                         } else {
7070                                 assert!(chan_msgs.1.is_none());
7071                         }
7072                         if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
7073                                 let commitment_update = chan_msgs.2.unwrap();
7074                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
7075                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
7076                                 }
7077                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
7078                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
7079                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
7080                                 for update_add in commitment_update.update_add_htlcs {
7081                                         node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add).unwrap();
7082                                 }
7083                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
7084                                         node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill).unwrap();
7085                                 }
7086                                 for update_fail in commitment_update.update_fail_htlcs {
7087                                         node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail).unwrap();
7088                                 }
7089
7090                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
7091                                         commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
7092                                 } else {
7093                                         node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
7094                                         check_added_monitors!(node_b, 1);
7095                                         let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
7096                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
7097                                         node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7098                                         assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
7099                                         check_added_monitors!(node_a, 1);
7100                                 }
7101                         } else {
7102                                 assert!(chan_msgs.2.is_none());
7103                         }
7104                 }
7105         }
7106
7107         #[test]
7108         fn test_simple_peer_disconnect() {
7109                 // Test that we can reconnect when there are no lost messages
7110                 let nodes = create_network(3);
7111                 create_announced_chan_between_nodes(&nodes, 0, 1);
7112                 create_announced_chan_between_nodes(&nodes, 1, 2);
7113
7114                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7115                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7116                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7117
7118                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7119                 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7120                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
7121                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
7122
7123                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7124                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7125                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7126
7127                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7128                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7129                 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7130                 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7131
7132                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7133                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7134
7135                 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3);
7136                 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
7137
7138                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
7139                 {
7140                         let events = nodes[0].node.get_and_clear_pending_events();
7141                         assert_eq!(events.len(), 2);
7142                         match events[0] {
7143                                 Event::PaymentSent { payment_preimage } => {
7144                                         assert_eq!(payment_preimage, payment_preimage_3);
7145                                 },
7146                                 _ => panic!("Unexpected event"),
7147                         }
7148                         match events[1] {
7149                                 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
7150                                         assert_eq!(payment_hash, payment_hash_5);
7151                                         assert!(rejected_by_dest);
7152                                 },
7153                                 _ => panic!("Unexpected event"),
7154                         }
7155                 }
7156
7157                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
7158                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
7159         }
7160
7161         fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
7162                 // Test that we can reconnect when in-flight HTLC updates get dropped
7163                 let mut nodes = create_network(2);
7164                 if messages_delivered == 0 {
7165                         create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
7166                         // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
7167                 } else {
7168                         create_announced_chan_between_nodes(&nodes, 0, 1);
7169                 }
7170
7171                 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();
7172                 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7173
7174                 let payment_event = {
7175                         nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
7176                         check_added_monitors!(nodes[0], 1);
7177
7178                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7179                         assert_eq!(events.len(), 1);
7180                         SendEvent::from_event(events.remove(0))
7181                 };
7182                 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
7183
7184                 if messages_delivered < 2 {
7185                         // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
7186                 } else {
7187                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7188                         if messages_delivered >= 3 {
7189                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7190                                 check_added_monitors!(nodes[1], 1);
7191                                 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7192
7193                                 if messages_delivered >= 4 {
7194                                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7195                                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7196                                         check_added_monitors!(nodes[0], 1);
7197
7198                                         if messages_delivered >= 5 {
7199                                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
7200                                                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7201                                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7202                                                 check_added_monitors!(nodes[0], 1);
7203
7204                                                 if messages_delivered >= 6 {
7205                                                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7206                                                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7207                                                         check_added_monitors!(nodes[1], 1);
7208                                                 }
7209                                         }
7210                                 }
7211                         }
7212                 }
7213
7214                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7215                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7216                 if messages_delivered < 3 {
7217                         // Even if the funding_locked messages get exchanged, as long as nothing further was
7218                         // received on either side, both sides will need to resend them.
7219                         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
7220                 } else if messages_delivered == 3 {
7221                         // nodes[0] still wants its RAA + commitment_signed
7222                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
7223                 } else if messages_delivered == 4 {
7224                         // nodes[0] still wants its commitment_signed
7225                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
7226                 } else if messages_delivered == 5 {
7227                         // nodes[1] still wants its final RAA
7228                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
7229                 } else if messages_delivered == 6 {
7230                         // Everything was delivered...
7231                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7232                 }
7233
7234                 let events_1 = nodes[1].node.get_and_clear_pending_events();
7235                 assert_eq!(events_1.len(), 1);
7236                 match events_1[0] {
7237                         Event::PendingHTLCsForwardable { .. } => { },
7238                         _ => panic!("Unexpected event"),
7239                 };
7240
7241                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7242                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7243                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7244
7245                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7246                 nodes[1].node.process_pending_htlc_forwards();
7247
7248                 let events_2 = nodes[1].node.get_and_clear_pending_events();
7249                 assert_eq!(events_2.len(), 1);
7250                 match events_2[0] {
7251                         Event::PaymentReceived { ref payment_hash, amt } => {
7252                                 assert_eq!(payment_hash_1, *payment_hash);
7253                                 assert_eq!(amt, 1000000);
7254                         },
7255                         _ => panic!("Unexpected event"),
7256                 }
7257
7258                 nodes[1].node.claim_funds(payment_preimage_1);
7259                 check_added_monitors!(nodes[1], 1);
7260
7261                 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
7262                 assert_eq!(events_3.len(), 1);
7263                 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
7264                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
7265                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7266                                 assert!(updates.update_add_htlcs.is_empty());
7267                                 assert!(updates.update_fail_htlcs.is_empty());
7268                                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
7269                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
7270                                 assert!(updates.update_fee.is_none());
7271                                 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
7272                         },
7273                         _ => panic!("Unexpected event"),
7274                 };
7275
7276                 if messages_delivered >= 1 {
7277                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc).unwrap();
7278
7279                         let events_4 = nodes[0].node.get_and_clear_pending_events();
7280                         assert_eq!(events_4.len(), 1);
7281                         match events_4[0] {
7282                                 Event::PaymentSent { ref payment_preimage } => {
7283                                         assert_eq!(payment_preimage_1, *payment_preimage);
7284                                 },
7285                                 _ => panic!("Unexpected event"),
7286                         }
7287
7288                         if messages_delivered >= 2 {
7289                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
7290                                 check_added_monitors!(nodes[0], 1);
7291                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7292
7293                                 if messages_delivered >= 3 {
7294                                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7295                                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7296                                         check_added_monitors!(nodes[1], 1);
7297
7298                                         if messages_delivered >= 4 {
7299                                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
7300                                                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7301                                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7302                                                 check_added_monitors!(nodes[1], 1);
7303
7304                                                 if messages_delivered >= 5 {
7305                                                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7306                                                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7307                                                         check_added_monitors!(nodes[0], 1);
7308                                                 }
7309                                         }
7310                                 }
7311                         }
7312                 }
7313
7314                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7315                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7316                 if messages_delivered < 2 {
7317                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
7318                         //TODO: Deduplicate PaymentSent events, then enable this if:
7319                         //if messages_delivered < 1 {
7320                                 let events_4 = nodes[0].node.get_and_clear_pending_events();
7321                                 assert_eq!(events_4.len(), 1);
7322                                 match events_4[0] {
7323                                         Event::PaymentSent { ref payment_preimage } => {
7324                                                 assert_eq!(payment_preimage_1, *payment_preimage);
7325                                         },
7326                                         _ => panic!("Unexpected event"),
7327                                 }
7328                         //}
7329                 } else if messages_delivered == 2 {
7330                         // nodes[0] still wants its RAA + commitment_signed
7331                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
7332                 } else if messages_delivered == 3 {
7333                         // nodes[0] still wants its commitment_signed
7334                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
7335                 } else if messages_delivered == 4 {
7336                         // nodes[1] still wants its final RAA
7337                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
7338                 } else if messages_delivered == 5 {
7339                         // Everything was delivered...
7340                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7341                 }
7342
7343                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7344                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7345                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7346
7347                 // Channel should still work fine...
7348                 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
7349                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7350         }
7351
7352         #[test]
7353         fn test_drop_messages_peer_disconnect_a() {
7354                 do_test_drop_messages_peer_disconnect(0);
7355                 do_test_drop_messages_peer_disconnect(1);
7356                 do_test_drop_messages_peer_disconnect(2);
7357                 do_test_drop_messages_peer_disconnect(3);
7358         }
7359
7360         #[test]
7361         fn test_drop_messages_peer_disconnect_b() {
7362                 do_test_drop_messages_peer_disconnect(4);
7363                 do_test_drop_messages_peer_disconnect(5);
7364                 do_test_drop_messages_peer_disconnect(6);
7365         }
7366
7367         #[test]
7368         fn test_funding_peer_disconnect() {
7369                 // Test that we can lock in our funding tx while disconnected
7370                 let nodes = create_network(2);
7371                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
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
7376                 confirm_transaction(&nodes[0].chain_monitor, &tx, tx.version);
7377                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7378                 assert_eq!(events_1.len(), 1);
7379                 match events_1[0] {
7380                         MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7381                                 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7382                         },
7383                         _ => panic!("Unexpected event"),
7384                 }
7385
7386                 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7387
7388                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7389                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7390
7391                 confirm_transaction(&nodes[1].chain_monitor, &tx, tx.version);
7392                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7393                 assert_eq!(events_2.len(), 2);
7394                 match events_2[0] {
7395                         MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7396                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7397                         },
7398                         _ => panic!("Unexpected event"),
7399                 }
7400                 match events_2[1] {
7401                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ } => {
7402                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7403                         },
7404                         _ => panic!("Unexpected event"),
7405                 }
7406
7407                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7408
7409                 // TODO: We shouldn't need to manually pass list_usable_chanels here once we support
7410                 // rebroadcasting announcement_signatures upon reconnect.
7411
7412                 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();
7413                 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
7414                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
7415         }
7416
7417         #[test]
7418         fn test_drop_messages_peer_disconnect_dual_htlc() {
7419                 // Test that we can handle reconnecting when both sides of a channel have pending
7420                 // commitment_updates when we disconnect.
7421                 let mut nodes = create_network(2);
7422                 create_announced_chan_between_nodes(&nodes, 0, 1);
7423
7424                 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7425
7426                 // Now try to send a second payment which will fail to send
7427                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7428                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7429
7430                 nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
7431                 check_added_monitors!(nodes[0], 1);
7432
7433                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7434                 assert_eq!(events_1.len(), 1);
7435                 match events_1[0] {
7436                         MessageSendEvent::UpdateHTLCs { .. } => {},
7437                         _ => panic!("Unexpected event"),
7438                 }
7439
7440                 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7441                 check_added_monitors!(nodes[1], 1);
7442
7443                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7444                 assert_eq!(events_2.len(), 1);
7445                 match events_2[0] {
7446                         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 } } => {
7447                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7448                                 assert!(update_add_htlcs.is_empty());
7449                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7450                                 assert!(update_fail_htlcs.is_empty());
7451                                 assert!(update_fail_malformed_htlcs.is_empty());
7452                                 assert!(update_fee.is_none());
7453
7454                                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7455                                 let events_3 = nodes[0].node.get_and_clear_pending_events();
7456                                 assert_eq!(events_3.len(), 1);
7457                                 match events_3[0] {
7458                                         Event::PaymentSent { ref payment_preimage } => {
7459                                                 assert_eq!(*payment_preimage, payment_preimage_1);
7460                                         },
7461                                         _ => panic!("Unexpected event"),
7462                                 }
7463
7464                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
7465                                 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7466                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7467                                 check_added_monitors!(nodes[0], 1);
7468                         },
7469                         _ => panic!("Unexpected event"),
7470                 }
7471
7472                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7473                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7474
7475                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7476                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7477                 assert_eq!(reestablish_1.len(), 1);
7478                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7479                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7480                 assert_eq!(reestablish_2.len(), 1);
7481
7482                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7483                 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7484                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7485                 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7486
7487                 assert!(as_resp.0.is_none());
7488                 assert!(bs_resp.0.is_none());
7489
7490                 assert!(bs_resp.1.is_none());
7491                 assert!(bs_resp.2.is_none());
7492
7493                 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7494
7495                 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
7496                 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
7497                 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7498                 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7499                 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
7500                 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();
7501                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7502                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7503                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7504                 check_added_monitors!(nodes[1], 1);
7505
7506                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap();
7507                 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7508                 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
7509                 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
7510                 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
7511                 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
7512                 assert!(bs_second_commitment_signed.update_fee.is_none());
7513                 check_added_monitors!(nodes[1], 1);
7514
7515                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7516                 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7517                 assert!(as_commitment_signed.update_add_htlcs.is_empty());
7518                 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
7519                 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
7520                 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
7521                 assert!(as_commitment_signed.update_fee.is_none());
7522                 check_added_monitors!(nodes[0], 1);
7523
7524                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
7525                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7526                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7527                 check_added_monitors!(nodes[0], 1);
7528
7529                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
7530                 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7531                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7532                 check_added_monitors!(nodes[1], 1);
7533
7534                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7535                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7536                 check_added_monitors!(nodes[1], 1);
7537
7538                 let events_4 = nodes[1].node.get_and_clear_pending_events();
7539                 assert_eq!(events_4.len(), 1);
7540                 match events_4[0] {
7541                         Event::PendingHTLCsForwardable { .. } => { },
7542                         _ => panic!("Unexpected event"),
7543                 };
7544
7545                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7546                 nodes[1].node.process_pending_htlc_forwards();
7547
7548                 let events_5 = nodes[1].node.get_and_clear_pending_events();
7549                 assert_eq!(events_5.len(), 1);
7550                 match events_5[0] {
7551                         Event::PaymentReceived { ref payment_hash, amt: _ } => {
7552                                 assert_eq!(payment_hash_2, *payment_hash);
7553                         },
7554                         _ => panic!("Unexpected event"),
7555                 }
7556
7557                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
7558                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7559                 check_added_monitors!(nodes[0], 1);
7560
7561                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7562         }
7563
7564         #[test]
7565         fn test_simple_monitor_permanent_update_fail() {
7566                 // Test that we handle a simple permanent monitor update failure
7567                 let mut nodes = create_network(2);
7568                 create_announced_chan_between_nodes(&nodes, 0, 1);
7569
7570                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7571                 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7572
7573                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7574                 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route, payment_hash_1) {} else { panic!(); }
7575                 check_added_monitors!(nodes[0], 1);
7576
7577                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7578                 assert_eq!(events_1.len(), 2);
7579                 match events_1[0] {
7580                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7581                         _ => panic!("Unexpected event"),
7582                 };
7583                 match events_1[1] {
7584                         MessageSendEvent::HandleError { node_id, .. } => assert_eq!(node_id, nodes[1].node.get_our_node_id()),
7585                         _ => panic!("Unexpected event"),
7586                 };
7587
7588                 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7589                 // PaymentFailed event
7590
7591                 assert_eq!(nodes[0].node.list_channels().len(), 0);
7592         }
7593
7594         fn do_test_simple_monitor_temporary_update_fail(disconnect: bool) {
7595                 // Test that we can recover from a simple temporary monitor update failure optionally with
7596                 // a disconnect in between
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_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7602
7603                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7604                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_1) {} else { panic!(); }
7605                 check_added_monitors!(nodes[0], 1);
7606
7607                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7608                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7609                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7610
7611                 if disconnect {
7612                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7613                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7614                         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7615                 }
7616
7617                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7618                 nodes[0].node.test_restore_channel_monitor();
7619                 check_added_monitors!(nodes[0], 1);
7620
7621                 let mut events_2 = nodes[0].node.get_and_clear_pending_msg_events();
7622                 assert_eq!(events_2.len(), 1);
7623                 let payment_event = SendEvent::from_event(events_2.pop().unwrap());
7624                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7625                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7626                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7627
7628                 expect_pending_htlcs_forwardable!(nodes[1]);
7629
7630                 let events_3 = nodes[1].node.get_and_clear_pending_events();
7631                 assert_eq!(events_3.len(), 1);
7632                 match events_3[0] {
7633                         Event::PaymentReceived { ref payment_hash, amt } => {
7634                                 assert_eq!(payment_hash_1, *payment_hash);
7635                                 assert_eq!(amt, 1000000);
7636                         },
7637                         _ => panic!("Unexpected event"),
7638                 }
7639
7640                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_1);
7641
7642                 // Now set it to failed again...
7643                 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7644                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7645                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route, payment_hash_2) {} else { panic!(); }
7646                 check_added_monitors!(nodes[0], 1);
7647
7648                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7649                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7650                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7651
7652                 if disconnect {
7653                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7654                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7655                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7656                 }
7657
7658                 // ...and make sure we can force-close a TemporaryFailure channel with a PermanentFailure
7659                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7660                 nodes[0].node.test_restore_channel_monitor();
7661                 check_added_monitors!(nodes[0], 1);
7662
7663                 let events_5 = nodes[0].node.get_and_clear_pending_msg_events();
7664                 assert_eq!(events_5.len(), 1);
7665                 match events_5[0] {
7666                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7667                         _ => panic!("Unexpected event"),
7668                 }
7669
7670                 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7671                 // PaymentFailed event
7672
7673                 assert_eq!(nodes[0].node.list_channels().len(), 0);
7674         }
7675
7676         #[test]
7677         fn test_simple_monitor_temporary_update_fail() {
7678                 do_test_simple_monitor_temporary_update_fail(false);
7679                 do_test_simple_monitor_temporary_update_fail(true);
7680         }
7681
7682         fn do_test_monitor_temporary_update_fail(disconnect_count: usize) {
7683                 let disconnect_flags = 8 | 16;
7684
7685                 // Test that we can recover from a temporary monitor update failure with some in-flight
7686                 // HTLCs going on at the same time potentially with some disconnection thrown in.
7687                 // * First we route a payment, then get a temporary monitor update failure when trying to
7688                 //   route a second payment. We then claim the first payment.
7689                 // * If disconnect_count is set, we will disconnect at this point (which is likely as
7690                 //   TemporaryFailure likely indicates net disconnect which resulted in failing to update
7691                 //   the ChannelMonitor on a watchtower).
7692                 // * If !(disconnect_count & 16) we deliver a update_fulfill_htlc/CS for the first payment
7693                 //   immediately, otherwise we wait sconnect and deliver them via the reconnect
7694                 //   channel_reestablish processing (ie disconnect_count & 16 makes no sense if
7695                 //   disconnect_count & !disconnect_flags is 0).
7696                 // * We then update the channel monitor, reconnecting if disconnect_count is set and walk
7697                 //   through message sending, potentially disconnect/reconnecting multiple times based on
7698                 //   disconnect_count, to get the update_fulfill_htlc through.
7699                 // * We then walk through more message exchanges to get the original update_add_htlc
7700                 //   through, swapping message ordering based on disconnect_count & 8 and optionally
7701                 //   disconnect/reconnecting based on disconnect_count.
7702                 let mut nodes = create_network(2);
7703                 create_announced_chan_between_nodes(&nodes, 0, 1);
7704
7705                 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7706
7707                 // Now try to send a second payment which will fail to send
7708                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7709                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7710
7711                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7712                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_2) {} else { panic!(); }
7713                 check_added_monitors!(nodes[0], 1);
7714
7715                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7716                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7717                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7718
7719                 // Claim the previous payment, which will result in a update_fulfill_htlc/CS from nodes[1]
7720                 // but nodes[0] won't respond since it is frozen.
7721                 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7722                 check_added_monitors!(nodes[1], 1);
7723                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7724                 assert_eq!(events_2.len(), 1);
7725                 let (bs_initial_fulfill, bs_initial_commitment_signed) = match events_2[0] {
7726                         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 } } => {
7727                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7728                                 assert!(update_add_htlcs.is_empty());
7729                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7730                                 assert!(update_fail_htlcs.is_empty());
7731                                 assert!(update_fail_malformed_htlcs.is_empty());
7732                                 assert!(update_fee.is_none());
7733
7734                                 if (disconnect_count & 16) == 0 {
7735                                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7736                                         let events_3 = nodes[0].node.get_and_clear_pending_events();
7737                                         assert_eq!(events_3.len(), 1);
7738                                         match events_3[0] {
7739                                                 Event::PaymentSent { ref payment_preimage } => {
7740                                                         assert_eq!(*payment_preimage, payment_preimage_1);
7741                                                 },
7742                                                 _ => panic!("Unexpected event"),
7743                                         }
7744
7745                                         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) {
7746                                                 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
7747                                         } else { panic!(); }
7748                                 }
7749
7750                                 (update_fulfill_htlcs[0].clone(), commitment_signed.clone())
7751                         },
7752                         _ => panic!("Unexpected event"),
7753                 };
7754
7755                 if disconnect_count & !disconnect_flags > 0 {
7756                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7757                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7758                 }
7759
7760                 // Now fix monitor updating...
7761                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7762                 nodes[0].node.test_restore_channel_monitor();
7763                 check_added_monitors!(nodes[0], 1);
7764
7765                 macro_rules! disconnect_reconnect_peers { () => { {
7766                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7767                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7768
7769                         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7770                         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7771                         assert_eq!(reestablish_1.len(), 1);
7772                         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7773                         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7774                         assert_eq!(reestablish_2.len(), 1);
7775
7776                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7777                         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7778                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7779                         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7780
7781                         assert!(as_resp.0.is_none());
7782                         assert!(bs_resp.0.is_none());
7783
7784                         (reestablish_1, reestablish_2, as_resp, bs_resp)
7785                 } } }
7786
7787                 let (payment_event, initial_revoke_and_ack) = if disconnect_count & !disconnect_flags > 0 {
7788                         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7789                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7790
7791                         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7792                         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7793                         assert_eq!(reestablish_1.len(), 1);
7794                         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7795                         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7796                         assert_eq!(reestablish_2.len(), 1);
7797
7798                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7799                         check_added_monitors!(nodes[0], 0);
7800                         let mut as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7801                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7802                         check_added_monitors!(nodes[1], 0);
7803                         let mut bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7804
7805                         assert!(as_resp.0.is_none());
7806                         assert!(bs_resp.0.is_none());
7807
7808                         assert!(bs_resp.1.is_none());
7809                         if (disconnect_count & 16) == 0 {
7810                                 assert!(bs_resp.2.is_none());
7811
7812                                 assert!(as_resp.1.is_some());
7813                                 assert!(as_resp.2.is_some());
7814                                 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7815                         } else {
7816                                 assert!(bs_resp.2.as_ref().unwrap().update_add_htlcs.is_empty());
7817                                 assert!(bs_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7818                                 assert!(bs_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7819                                 assert!(bs_resp.2.as_ref().unwrap().update_fee.is_none());
7820                                 assert!(bs_resp.2.as_ref().unwrap().update_fulfill_htlcs == vec![bs_initial_fulfill]);
7821                                 assert!(bs_resp.2.as_ref().unwrap().commitment_signed == bs_initial_commitment_signed);
7822
7823                                 assert!(as_resp.1.is_none());
7824
7825                                 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();
7826                                 let events_3 = nodes[0].node.get_and_clear_pending_events();
7827                                 assert_eq!(events_3.len(), 1);
7828                                 match events_3[0] {
7829                                         Event::PaymentSent { ref payment_preimage } => {
7830                                                 assert_eq!(*payment_preimage, payment_preimage_1);
7831                                         },
7832                                         _ => panic!("Unexpected event"),
7833                                 }
7834
7835                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7836                                 let as_resp_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7837                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7838                                 check_added_monitors!(nodes[0], 1);
7839
7840                                 as_resp.1 = Some(as_resp_raa);
7841                                 bs_resp.2 = None;
7842                         }
7843
7844                         if disconnect_count & !disconnect_flags > 1 {
7845                                 let (second_reestablish_1, second_reestablish_2, second_as_resp, second_bs_resp) = disconnect_reconnect_peers!();
7846
7847                                 if (disconnect_count & 16) == 0 {
7848                                         assert!(reestablish_1 == second_reestablish_1);
7849                                         assert!(reestablish_2 == second_reestablish_2);
7850                                 }
7851                                 assert!(as_resp == second_as_resp);
7852                                 assert!(bs_resp == second_bs_resp);
7853                         }
7854
7855                         (SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), as_resp.2.unwrap()), as_resp.1.unwrap())
7856                 } else {
7857                         let mut events_4 = nodes[0].node.get_and_clear_pending_msg_events();
7858                         assert_eq!(events_4.len(), 2);
7859                         (SendEvent::from_event(events_4.remove(0)), match events_4[0] {
7860                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
7861                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7862                                         msg.clone()
7863                                 },
7864                                 _ => panic!("Unexpected event"),
7865                         })
7866                 };
7867
7868                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7869
7870                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7871                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7872                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7873                 // nodes[1] is awaiting an RAA from nodes[0] still so get_event_msg's assert(len == 1) passes
7874                 check_added_monitors!(nodes[1], 1);
7875
7876                 if disconnect_count & !disconnect_flags > 2 {
7877                         let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7878
7879                         assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7880                         assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7881
7882                         assert!(as_resp.2.is_none());
7883                         assert!(bs_resp.2.is_none());
7884                 }
7885
7886                 let as_commitment_update;
7887                 let bs_second_commitment_update;
7888
7889                 macro_rules! handle_bs_raa { () => {
7890                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7891                         as_commitment_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7892                         assert!(as_commitment_update.update_add_htlcs.is_empty());
7893                         assert!(as_commitment_update.update_fulfill_htlcs.is_empty());
7894                         assert!(as_commitment_update.update_fail_htlcs.is_empty());
7895                         assert!(as_commitment_update.update_fail_malformed_htlcs.is_empty());
7896                         assert!(as_commitment_update.update_fee.is_none());
7897                         check_added_monitors!(nodes[0], 1);
7898                 } }
7899
7900                 macro_rules! handle_initial_raa { () => {
7901                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &initial_revoke_and_ack).unwrap();
7902                         bs_second_commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7903                         assert!(bs_second_commitment_update.update_add_htlcs.is_empty());
7904                         assert!(bs_second_commitment_update.update_fulfill_htlcs.is_empty());
7905                         assert!(bs_second_commitment_update.update_fail_htlcs.is_empty());
7906                         assert!(bs_second_commitment_update.update_fail_malformed_htlcs.is_empty());
7907                         assert!(bs_second_commitment_update.update_fee.is_none());
7908                         check_added_monitors!(nodes[1], 1);
7909                 } }
7910
7911                 if (disconnect_count & 8) == 0 {
7912                         handle_bs_raa!();
7913
7914                         if disconnect_count & !disconnect_flags > 3 {
7915                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7916
7917                                 assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7918                                 assert!(bs_resp.1.is_none());
7919
7920                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7921                                 assert!(bs_resp.2.is_none());
7922
7923                                 assert!(as_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7924                         }
7925
7926                         handle_initial_raa!();
7927
7928                         if disconnect_count & !disconnect_flags > 4 {
7929                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7930
7931                                 assert!(as_resp.1.is_none());
7932                                 assert!(bs_resp.1.is_none());
7933
7934                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7935                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7936                         }
7937                 } else {
7938                         handle_initial_raa!();
7939
7940                         if disconnect_count & !disconnect_flags > 3 {
7941                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7942
7943                                 assert!(as_resp.1.is_none());
7944                                 assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7945
7946                                 assert!(as_resp.2.is_none());
7947                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7948
7949                                 assert!(bs_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7950                         }
7951
7952                         handle_bs_raa!();
7953
7954                         if disconnect_count & !disconnect_flags > 4 {
7955                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7956
7957                                 assert!(as_resp.1.is_none());
7958                                 assert!(bs_resp.1.is_none());
7959
7960                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7961                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7962                         }
7963                 }
7964
7965                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_update.commitment_signed).unwrap();
7966                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7967                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7968                 check_added_monitors!(nodes[0], 1);
7969
7970                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_update.commitment_signed).unwrap();
7971                 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7972                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7973                 check_added_monitors!(nodes[1], 1);
7974
7975                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7976                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7977                 check_added_monitors!(nodes[1], 1);
7978
7979                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
7980                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7981                 check_added_monitors!(nodes[0], 1);
7982
7983                 expect_pending_htlcs_forwardable!(nodes[1]);
7984
7985                 let events_5 = nodes[1].node.get_and_clear_pending_events();
7986                 assert_eq!(events_5.len(), 1);
7987                 match events_5[0] {
7988                         Event::PaymentReceived { ref payment_hash, amt } => {
7989                                 assert_eq!(payment_hash_2, *payment_hash);
7990                                 assert_eq!(amt, 1000000);
7991                         },
7992                         _ => panic!("Unexpected event"),
7993                 }
7994
7995                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7996         }
7997
7998         #[test]
7999         fn test_monitor_temporary_update_fail_a() {
8000                 do_test_monitor_temporary_update_fail(0);
8001                 do_test_monitor_temporary_update_fail(1);
8002                 do_test_monitor_temporary_update_fail(2);
8003                 do_test_monitor_temporary_update_fail(3);
8004                 do_test_monitor_temporary_update_fail(4);
8005                 do_test_monitor_temporary_update_fail(5);
8006         }
8007
8008         #[test]
8009         fn test_monitor_temporary_update_fail_b() {
8010                 do_test_monitor_temporary_update_fail(2 | 8);
8011                 do_test_monitor_temporary_update_fail(3 | 8);
8012                 do_test_monitor_temporary_update_fail(4 | 8);
8013                 do_test_monitor_temporary_update_fail(5 | 8);
8014         }
8015
8016         #[test]
8017         fn test_monitor_temporary_update_fail_c() {
8018                 do_test_monitor_temporary_update_fail(1 | 16);
8019                 do_test_monitor_temporary_update_fail(2 | 16);
8020                 do_test_monitor_temporary_update_fail(3 | 16);
8021                 do_test_monitor_temporary_update_fail(2 | 8 | 16);
8022                 do_test_monitor_temporary_update_fail(3 | 8 | 16);
8023         }
8024
8025         #[test]
8026         fn test_monitor_update_fail_cs() {
8027                 // Tests handling of a monitor update failure when processing an incoming commitment_signed
8028                 let mut nodes = create_network(2);
8029                 create_announced_chan_between_nodes(&nodes, 0, 1);
8030
8031                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8032                 let (payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
8033                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
8034                 check_added_monitors!(nodes[0], 1);
8035
8036                 let send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8037                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8038
8039                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8040                 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() {
8041                         assert_eq!(err, "Failed to update ChannelMonitor");
8042                 } else { panic!(); }
8043                 check_added_monitors!(nodes[1], 1);
8044                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8045
8046                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8047                 nodes[1].node.test_restore_channel_monitor();
8048                 check_added_monitors!(nodes[1], 1);
8049                 let responses = nodes[1].node.get_and_clear_pending_msg_events();
8050                 assert_eq!(responses.len(), 2);
8051
8052                 match responses[0] {
8053                         MessageSendEvent::SendRevokeAndACK { ref msg, ref node_id } => {
8054                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8055                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &msg).unwrap();
8056                                 check_added_monitors!(nodes[0], 1);
8057                         },
8058                         _ => panic!("Unexpected event"),
8059                 }
8060                 match responses[1] {
8061                         MessageSendEvent::UpdateHTLCs { ref updates, ref node_id } => {
8062                                 assert!(updates.update_add_htlcs.is_empty());
8063                                 assert!(updates.update_fulfill_htlcs.is_empty());
8064                                 assert!(updates.update_fail_htlcs.is_empty());
8065                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8066                                 assert!(updates.update_fee.is_none());
8067                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8068
8069                                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8070                                 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() {
8071                                         assert_eq!(err, "Failed to update ChannelMonitor");
8072                                 } else { panic!(); }
8073                                 check_added_monitors!(nodes[0], 1);
8074                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8075                         },
8076                         _ => panic!("Unexpected event"),
8077                 }
8078
8079                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
8080                 nodes[0].node.test_restore_channel_monitor();
8081                 check_added_monitors!(nodes[0], 1);
8082
8083                 let final_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8084                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &final_raa).unwrap();
8085                 check_added_monitors!(nodes[1], 1);
8086
8087                 let mut events = nodes[1].node.get_and_clear_pending_events();
8088                 assert_eq!(events.len(), 1);
8089                 match events[0] {
8090                         Event::PendingHTLCsForwardable { .. } => { },
8091                         _ => panic!("Unexpected event"),
8092                 };
8093                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8094                 nodes[1].node.process_pending_htlc_forwards();
8095
8096                 events = nodes[1].node.get_and_clear_pending_events();
8097                 assert_eq!(events.len(), 1);
8098                 match events[0] {
8099                         Event::PaymentReceived { payment_hash, amt } => {
8100                                 assert_eq!(payment_hash, our_payment_hash);
8101                                 assert_eq!(amt, 1000000);
8102                         },
8103                         _ => panic!("Unexpected event"),
8104                 };
8105
8106                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
8107         }
8108
8109         fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) {
8110                 // Tests handling of a monitor update failure when processing an incoming RAA
8111                 let mut nodes = create_network(3);
8112                 create_announced_chan_between_nodes(&nodes, 0, 1);
8113                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
8114
8115                 // Rebalance a bit so that we can send backwards from 2 to 1.
8116                 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 5000000);
8117
8118                 // Route a first payment that we'll fail backwards
8119                 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
8120
8121                 // Fail the payment backwards, failing the monitor update on nodes[1]'s receipt of the RAA
8122                 assert!(nodes[2].node.fail_htlc_backwards(&payment_hash_1, 0));
8123                 check_added_monitors!(nodes[2], 1);
8124
8125                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8126                 assert!(updates.update_add_htlcs.is_empty());
8127                 assert!(updates.update_fulfill_htlcs.is_empty());
8128                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8129                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8130                 assert!(updates.update_fee.is_none());
8131                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
8132
8133                 let bs_revoke_and_ack = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
8134                 check_added_monitors!(nodes[0], 0);
8135
8136                 // While the second channel is AwaitingRAA, forward a second payment to get it into the
8137                 // holding cell.
8138                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
8139                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8140                 nodes[0].node.send_payment(route, payment_hash_2).unwrap();
8141                 check_added_monitors!(nodes[0], 1);
8142
8143                 let mut send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8144                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8145                 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false);
8146
8147                 let events_1 = nodes[1].node.get_and_clear_pending_events();
8148                 assert_eq!(events_1.len(), 1);
8149                 match events_1[0] {
8150                         Event::PendingHTLCsForwardable { .. } => { },
8151                         _ => panic!("Unexpected event"),
8152                 };
8153
8154                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8155                 nodes[1].node.process_pending_htlc_forwards();
8156                 check_added_monitors!(nodes[1], 0);
8157                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8158
8159                 // Now fail monitor updating.
8160                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8161                 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() {
8162                         assert_eq!(err, "Failed to update ChannelMonitor");
8163                 } else { panic!(); }
8164                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8165                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8166                 check_added_monitors!(nodes[1], 1);
8167
8168                 // Attempt to forward a third payment but fail due to the second channel being unavailable
8169                 // for forwarding.
8170
8171                 let (_, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
8172                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8173                 nodes[0].node.send_payment(route, payment_hash_3).unwrap();
8174                 check_added_monitors!(nodes[0], 1);
8175
8176                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(()); // We succeed in updating the monitor for the first channel
8177                 send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8178                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8179                 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
8180                 check_added_monitors!(nodes[1], 0);
8181
8182                 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8183                 assert_eq!(events_2.len(), 1);
8184                 match events_2.remove(0) {
8185                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
8186                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8187                                 assert!(updates.update_fulfill_htlcs.is_empty());
8188                                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8189                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8190                                 assert!(updates.update_add_htlcs.is_empty());
8191                                 assert!(updates.update_fee.is_none());
8192
8193                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
8194                                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
8195
8196                                 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
8197                                 assert_eq!(msg_events.len(), 1);
8198                                 match msg_events[0] {
8199                                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
8200                                                 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
8201                                                 assert_eq!(msg.contents.flags & 2, 2); // temp disabled
8202                                         },
8203                                         _ => panic!("Unexpected event"),
8204                                 }
8205
8206                                 let events = nodes[0].node.get_and_clear_pending_events();
8207                                 assert_eq!(events.len(), 1);
8208                                 if let Event::PaymentFailed { payment_hash, rejected_by_dest, .. } = events[0] {
8209                                         assert_eq!(payment_hash, payment_hash_3);
8210                                         assert!(!rejected_by_dest);
8211                                 } else { panic!("Unexpected event!"); }
8212                         },
8213                         _ => panic!("Unexpected event type!"),
8214                 };
8215
8216                 let (payment_preimage_4, payment_hash_4) = if test_ignore_second_cs {
8217                         // Try to route another payment backwards from 2 to make sure 1 holds off on responding
8218                         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[0]);
8219                         let route = nodes[2].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8220                         nodes[2].node.send_payment(route, payment_hash_4).unwrap();
8221                         check_added_monitors!(nodes[2], 1);
8222
8223                         send_event = SendEvent::from_event(nodes[2].node.get_and_clear_pending_msg_events().remove(0));
8224                         nodes[1].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8225                         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) {
8226                                 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
8227                         } else { panic!(); }
8228                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8229                         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8230                         (Some(payment_preimage_4), Some(payment_hash_4))
8231                 } else { (None, None) };
8232
8233                 // Restore monitor updating, ensuring we immediately get a fail-back update and a
8234                 // update_add update.
8235                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8236                 nodes[1].node.test_restore_channel_monitor();
8237                 check_added_monitors!(nodes[1], 2);
8238
8239                 let mut events_3 = nodes[1].node.get_and_clear_pending_msg_events();
8240                 if test_ignore_second_cs {
8241                         assert_eq!(events_3.len(), 3);
8242                 } else {
8243                         assert_eq!(events_3.len(), 2);
8244                 }
8245
8246                 // Note that the ordering of the events for different nodes is non-prescriptive, though the
8247                 // ordering of the two events that both go to nodes[2] have to stay in the same order.
8248                 let messages_a = match events_3.pop().unwrap() {
8249                         MessageSendEvent::UpdateHTLCs { node_id, mut updates } => {
8250                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8251                                 assert!(updates.update_fulfill_htlcs.is_empty());
8252                                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8253                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8254                                 assert!(updates.update_add_htlcs.is_empty());
8255                                 assert!(updates.update_fee.is_none());
8256                                 (updates.update_fail_htlcs.remove(0), updates.commitment_signed)
8257                         },
8258                         _ => panic!("Unexpected event type!"),
8259                 };
8260                 let raa = if test_ignore_second_cs {
8261                         match events_3.remove(1) {
8262                                 MessageSendEvent::SendRevokeAndACK { node_id, msg } => {
8263                                         assert_eq!(node_id, nodes[2].node.get_our_node_id());
8264                                         Some(msg.clone())
8265                                 },
8266                                 _ => panic!("Unexpected event"),
8267                         }
8268                 } else { None };
8269                 let send_event_b = SendEvent::from_event(events_3.remove(0));
8270                 assert_eq!(send_event_b.node_id, nodes[2].node.get_our_node_id());
8271
8272                 // Now deliver the new messages...
8273
8274                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &messages_a.0).unwrap();
8275                 commitment_signed_dance!(nodes[0], nodes[1], messages_a.1, false);
8276                 let events_4 = nodes[0].node.get_and_clear_pending_events();
8277                 assert_eq!(events_4.len(), 1);
8278                 if let Event::PaymentFailed { payment_hash, rejected_by_dest, .. } = events_4[0] {
8279                         assert_eq!(payment_hash, payment_hash_1);
8280                         assert!(rejected_by_dest);
8281                 } else { panic!("Unexpected event!"); }
8282
8283                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event_b.msgs[0]).unwrap();
8284                 if test_ignore_second_cs {
8285                         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event_b.commitment_msg).unwrap();
8286                         check_added_monitors!(nodes[2], 1);
8287                         let bs_revoke_and_ack = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8288                         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa.unwrap()).unwrap();
8289                         check_added_monitors!(nodes[2], 1);
8290                         let bs_cs = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8291                         assert!(bs_cs.update_add_htlcs.is_empty());
8292                         assert!(bs_cs.update_fail_htlcs.is_empty());
8293                         assert!(bs_cs.update_fail_malformed_htlcs.is_empty());
8294                         assert!(bs_cs.update_fulfill_htlcs.is_empty());
8295                         assert!(bs_cs.update_fee.is_none());
8296
8297                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
8298                         check_added_monitors!(nodes[1], 1);
8299                         let as_cs = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
8300                         assert!(as_cs.update_add_htlcs.is_empty());
8301                         assert!(as_cs.update_fail_htlcs.is_empty());
8302                         assert!(as_cs.update_fail_malformed_htlcs.is_empty());
8303                         assert!(as_cs.update_fulfill_htlcs.is_empty());
8304                         assert!(as_cs.update_fee.is_none());
8305
8306                         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_cs.commitment_signed).unwrap();
8307                         check_added_monitors!(nodes[1], 1);
8308                         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
8309
8310                         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_cs.commitment_signed).unwrap();
8311                         check_added_monitors!(nodes[2], 1);
8312                         let bs_second_raa = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8313
8314                         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
8315                         check_added_monitors!(nodes[2], 1);
8316                         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
8317
8318                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_second_raa).unwrap();
8319                         check_added_monitors!(nodes[1], 1);
8320                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8321                 } else {
8322                         commitment_signed_dance!(nodes[2], nodes[1], send_event_b.commitment_msg, false);
8323                 }
8324
8325                 let events_5 = nodes[2].node.get_and_clear_pending_events();
8326                 assert_eq!(events_5.len(), 1);
8327                 match events_5[0] {
8328                         Event::PendingHTLCsForwardable { .. } => { },
8329                         _ => panic!("Unexpected event"),
8330                 };
8331
8332                 nodes[2].node.channel_state.lock().unwrap().next_forward = Instant::now();
8333                 nodes[2].node.process_pending_htlc_forwards();
8334
8335                 let events_6 = nodes[2].node.get_and_clear_pending_events();
8336                 assert_eq!(events_6.len(), 1);
8337                 match events_6[0] {
8338                         Event::PaymentReceived { payment_hash, .. } => { assert_eq!(payment_hash, payment_hash_2); },
8339                         _ => panic!("Unexpected event"),
8340                 };
8341
8342                 if test_ignore_second_cs {
8343                         let events_7 = nodes[1].node.get_and_clear_pending_events();
8344                         assert_eq!(events_7.len(), 1);
8345                         match events_7[0] {
8346                                 Event::PendingHTLCsForwardable { .. } => { },
8347                                 _ => panic!("Unexpected event"),
8348                         };
8349
8350                         nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8351                         nodes[1].node.process_pending_htlc_forwards();
8352                         check_added_monitors!(nodes[1], 1);
8353
8354                         send_event = SendEvent::from_node(&nodes[1]);
8355                         assert_eq!(send_event.node_id, nodes[0].node.get_our_node_id());
8356                         assert_eq!(send_event.msgs.len(), 1);
8357                         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8358                         commitment_signed_dance!(nodes[0], nodes[1], send_event.commitment_msg, false);
8359
8360                         let events_8 = nodes[0].node.get_and_clear_pending_events();
8361                         assert_eq!(events_8.len(), 1);
8362                         match events_8[0] {
8363                                 Event::PendingHTLCsForwardable { .. } => { },
8364                                 _ => panic!("Unexpected event"),
8365                         };
8366
8367                         nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
8368                         nodes[0].node.process_pending_htlc_forwards();
8369
8370                         let events_9 = nodes[0].node.get_and_clear_pending_events();
8371                         assert_eq!(events_9.len(), 1);
8372                         match events_9[0] {
8373                                 Event::PaymentReceived { payment_hash, .. } => assert_eq!(payment_hash, payment_hash_4.unwrap()),
8374                                 _ => panic!("Unexpected event"),
8375                         };
8376                         claim_payment(&nodes[2], &[&nodes[1], &nodes[0]], payment_preimage_4.unwrap());
8377                 }
8378
8379                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
8380         }
8381
8382         #[test]
8383         fn test_monitor_update_fail_raa() {
8384                 do_test_monitor_update_fail_raa(false);
8385                 do_test_monitor_update_fail_raa(true);
8386         }
8387
8388         #[test]
8389         fn test_monitor_update_fail_reestablish() {
8390                 // Simple test for message retransmission after monitor update failure on
8391                 // channel_reestablish generating a monitor update (which comes from freeing holding cell
8392                 // HTLCs).
8393                 let mut nodes = create_network(3);
8394                 create_announced_chan_between_nodes(&nodes, 0, 1);
8395                 create_announced_chan_between_nodes(&nodes, 1, 2);
8396
8397                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
8398
8399                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8400                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8401
8402                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
8403                 check_added_monitors!(nodes[2], 1);
8404                 let mut updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8405                 assert!(updates.update_add_htlcs.is_empty());
8406                 assert!(updates.update_fail_htlcs.is_empty());
8407                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8408                 assert!(updates.update_fee.is_none());
8409                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8410                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8411                 check_added_monitors!(nodes[1], 1);
8412                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8413                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
8414
8415                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8416                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8417                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8418
8419                 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
8420                 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8421
8422                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
8423
8424                 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() {
8425                         assert_eq!(err, "Failed to update ChannelMonitor");
8426                 } else { panic!(); }
8427                 check_added_monitors!(nodes[1], 1);
8428
8429                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8430                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8431
8432                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8433                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8434
8435                 assert!(as_reestablish == get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()));
8436                 assert!(bs_reestablish == get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id()));
8437
8438                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
8439
8440                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish).unwrap();
8441                 check_added_monitors!(nodes[1], 0);
8442                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8443
8444                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8445                 nodes[1].node.test_restore_channel_monitor();
8446                 check_added_monitors!(nodes[1], 1);
8447
8448                 updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8449                 assert!(updates.update_add_htlcs.is_empty());
8450                 assert!(updates.update_fail_htlcs.is_empty());
8451                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8452                 assert!(updates.update_fee.is_none());
8453                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8454                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8455                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
8456
8457                 let events = nodes[0].node.get_and_clear_pending_events();
8458                 assert_eq!(events.len(), 1);
8459                 match events[0] {
8460                         Event::PaymentSent { payment_preimage, .. } => assert_eq!(payment_preimage, our_payment_preimage),
8461                         _ => panic!("Unexpected event"),
8462                 }
8463         }
8464
8465         #[test]
8466         fn test_invalid_channel_announcement() {
8467                 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
8468                 let secp_ctx = Secp256k1::new();
8469                 let nodes = create_network(2);
8470
8471                 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1]);
8472
8473                 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8474                 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
8475                 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
8476                 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
8477
8478                 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 } );
8479
8480                 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
8481                 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
8482
8483                 let as_network_key = nodes[0].node.get_our_node_id();
8484                 let bs_network_key = nodes[1].node.get_our_node_id();
8485
8486                 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
8487
8488                 let mut chan_announcement;
8489
8490                 macro_rules! dummy_unsigned_msg {
8491                         () => {
8492                                 msgs::UnsignedChannelAnnouncement {
8493                                         features: msgs::GlobalFeatures::new(),
8494                                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
8495                                         short_channel_id: as_chan.get_short_channel_id().unwrap(),
8496                                         node_id_1: if were_node_one { as_network_key } else { bs_network_key },
8497                                         node_id_2: if were_node_one { bs_network_key } else { as_network_key },
8498                                         bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
8499                                         bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
8500                                         excess_data: Vec::new(),
8501                                 };
8502                         }
8503                 }
8504
8505                 macro_rules! sign_msg {
8506                         ($unsigned_msg: expr) => {
8507                                 let msghash = Message::from_slice(&Sha256dHash::from_data(&$unsigned_msg.encode()[..])[..]).unwrap();
8508                                 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
8509                                 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
8510                                 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].node.our_network_key);
8511                                 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].node.our_network_key);
8512                                 chan_announcement = msgs::ChannelAnnouncement {
8513                                         node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
8514                                         node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
8515                                         bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
8516                                         bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
8517                                         contents: $unsigned_msg
8518                                 }
8519                         }
8520                 }
8521
8522                 let unsigned_msg = dummy_unsigned_msg!();
8523                 sign_msg!(unsigned_msg);
8524                 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
8525                 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 } );
8526
8527                 // Configured with Network::Testnet
8528                 let mut unsigned_msg = dummy_unsigned_msg!();
8529                 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
8530                 sign_msg!(unsigned_msg);
8531                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
8532
8533                 let mut unsigned_msg = dummy_unsigned_msg!();
8534                 unsigned_msg.chain_hash = Sha256dHash::from_data(&[1,2,3,4,5,6,7,8,9]);
8535                 sign_msg!(unsigned_msg);
8536                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
8537         }
8538
8539         struct VecWriter(Vec<u8>);
8540         impl Writer for VecWriter {
8541                 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
8542                         self.0.extend_from_slice(buf);
8543                         Ok(())
8544                 }
8545                 fn size_hint(&mut self, size: usize) {
8546                         self.0.reserve_exact(size);
8547                 }
8548         }
8549
8550         #[test]
8551         fn test_no_txn_manager_serialize_deserialize() {
8552                 let mut nodes = create_network(2);
8553
8554                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
8555
8556                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8557
8558                 let nodes_0_serialized = nodes[0].node.encode();
8559                 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8560                 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8561
8562                 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())));
8563                 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8564                 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8565                 assert!(chan_0_monitor_read.is_empty());
8566
8567                 let mut nodes_0_read = &nodes_0_serialized[..];
8568                 let config = UserConfig::new();
8569                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8570                 let (_, nodes_0_deserialized) = {
8571                         let mut channel_monitors = HashMap::new();
8572                         channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8573                         <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8574                                 default_config: config,
8575                                 keys_manager,
8576                                 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8577                                 monitor: nodes[0].chan_monitor.clone(),
8578                                 chain_monitor: nodes[0].chain_monitor.clone(),
8579                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8580                                 logger: Arc::new(test_utils::TestLogger::new()),
8581                                 channel_monitors: &channel_monitors,
8582                         }).unwrap()
8583                 };
8584                 assert!(nodes_0_read.is_empty());
8585
8586                 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8587                 nodes[0].node = Arc::new(nodes_0_deserialized);
8588                 let nodes_0_as_listener: Arc<ChainListener> = nodes[0].node.clone();
8589                 nodes[0].chain_monitor.register_listener(Arc::downgrade(&nodes_0_as_listener));
8590                 assert_eq!(nodes[0].node.list_channels().len(), 1);
8591                 check_added_monitors!(nodes[0], 1);
8592
8593                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8594                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
8595                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8596                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
8597
8598                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
8599                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8600                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
8601                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8602
8603                 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8604                 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8605                 for node in nodes.iter() {
8606                         assert!(node.router.handle_channel_announcement(&announcement).unwrap());
8607                         node.router.handle_channel_update(&as_update).unwrap();
8608                         node.router.handle_channel_update(&bs_update).unwrap();
8609                 }
8610
8611                 send_payment(&nodes[0], &[&nodes[1]], 1000000);
8612         }
8613
8614         #[test]
8615         fn test_simple_manager_serialize_deserialize() {
8616                 let mut nodes = create_network(2);
8617                 create_announced_chan_between_nodes(&nodes, 0, 1);
8618
8619                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8620                 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8621
8622                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8623
8624                 let nodes_0_serialized = nodes[0].node.encode();
8625                 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8626                 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8627
8628                 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())));
8629                 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8630                 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8631                 assert!(chan_0_monitor_read.is_empty());
8632
8633                 let mut nodes_0_read = &nodes_0_serialized[..];
8634                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8635                 let (_, nodes_0_deserialized) = {
8636                         let mut channel_monitors = HashMap::new();
8637                         channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8638                         <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8639                                 default_config: UserConfig::new(),
8640                                 keys_manager,
8641                                 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8642                                 monitor: nodes[0].chan_monitor.clone(),
8643                                 chain_monitor: nodes[0].chain_monitor.clone(),
8644                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8645                                 logger: Arc::new(test_utils::TestLogger::new()),
8646                                 channel_monitors: &channel_monitors,
8647                         }).unwrap()
8648                 };
8649                 assert!(nodes_0_read.is_empty());
8650
8651                 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8652                 nodes[0].node = Arc::new(nodes_0_deserialized);
8653                 check_added_monitors!(nodes[0], 1);
8654
8655                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8656
8657                 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
8658                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
8659         }
8660
8661         #[test]
8662         fn test_manager_serialize_deserialize_inconsistent_monitor() {
8663                 // Test deserializing a ChannelManager with a out-of-date ChannelMonitor
8664                 let mut nodes = create_network(4);
8665                 create_announced_chan_between_nodes(&nodes, 0, 1);
8666                 create_announced_chan_between_nodes(&nodes, 2, 0);
8667                 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3);
8668
8669                 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
8670
8671                 // Serialize the ChannelManager here, but the monitor we keep up-to-date
8672                 let nodes_0_serialized = nodes[0].node.encode();
8673
8674                 route_payment(&nodes[0], &[&nodes[3]], 1000000);
8675                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8676                 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8677                 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8678
8679                 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
8680                 // nodes[3])
8681                 let mut node_0_monitors_serialized = Vec::new();
8682                 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
8683                         let mut writer = VecWriter(Vec::new());
8684                         monitor.1.write_for_disk(&mut writer).unwrap();
8685                         node_0_monitors_serialized.push(writer.0);
8686                 }
8687
8688                 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())));
8689                 let mut node_0_monitors = Vec::new();
8690                 for serialized in node_0_monitors_serialized.iter() {
8691                         let mut read = &serialized[..];
8692                         let (_, monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
8693                         assert!(read.is_empty());
8694                         node_0_monitors.push(monitor);
8695                 }
8696
8697                 let mut nodes_0_read = &nodes_0_serialized[..];
8698                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8699                 let (_, nodes_0_deserialized) = <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8700                         default_config: UserConfig::new(),
8701                         keys_manager,
8702                         fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8703                         monitor: nodes[0].chan_monitor.clone(),
8704                         chain_monitor: nodes[0].chain_monitor.clone(),
8705                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8706                         logger: Arc::new(test_utils::TestLogger::new()),
8707                         channel_monitors: &node_0_monitors.iter().map(|monitor| { (monitor.get_funding_txo().unwrap(), monitor) }).collect(),
8708                 }).unwrap();
8709                 assert!(nodes_0_read.is_empty());
8710
8711                 { // Channel close should result in a commitment tx and an HTLC tx
8712                         let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8713                         assert_eq!(txn.len(), 2);
8714                         assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
8715                         assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
8716                 }
8717
8718                 for monitor in node_0_monitors.drain(..) {
8719                         assert!(nodes[0].chan_monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor).is_ok());
8720                         check_added_monitors!(nodes[0], 1);
8721                 }
8722                 nodes[0].node = Arc::new(nodes_0_deserialized);
8723
8724                 // nodes[1] and nodes[2] have no lost state with nodes[0]...
8725                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8726                 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8727                 //... and we can even still claim the payment!
8728                 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
8729
8730                 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id());
8731                 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8732                 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id());
8733                 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) {
8734                         assert_eq!(msg.channel_id, channel_id);
8735                 } else { panic!("Unexpected result"); }
8736         }
8737
8738         macro_rules! check_spendable_outputs {
8739                 ($node: expr, $der_idx: expr) => {
8740                         {
8741                                 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
8742                                 let mut txn = Vec::new();
8743                                 for event in events {
8744                                         match event {
8745                                                 Event::SpendableOutputs { ref outputs } => {
8746                                                         for outp in outputs {
8747                                                                 match *outp {
8748                                                                         SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
8749                                                                                 let input = TxIn {
8750                                                                                         previous_output: outpoint.clone(),
8751                                                                                         script_sig: Script::new(),
8752                                                                                         sequence: 0,
8753                                                                                         witness: Vec::new(),
8754                                                                                 };
8755                                                                                 let outp = TxOut {
8756                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8757                                                                                         value: output.value,
8758                                                                                 };
8759                                                                                 let mut spend_tx = Transaction {
8760                                                                                         version: 2,
8761                                                                                         lock_time: 0,
8762                                                                                         input: vec![input],
8763                                                                                         output: vec![outp],
8764                                                                                 };
8765                                                                                 let secp_ctx = Secp256k1::new();
8766                                                                                 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
8767                                                                                 let witness_script = Address::p2pkh(&remotepubkey, Network::Testnet).script_pubkey();
8768                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8769                                                                                 let remotesig = secp_ctx.sign(&sighash, key);
8770                                                                                 spend_tx.input[0].witness.push(remotesig.serialize_der(&secp_ctx).to_vec());
8771                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8772                                                                                 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
8773                                                                                 txn.push(spend_tx);
8774                                                                         },
8775                                                                         SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
8776                                                                                 let input = TxIn {
8777                                                                                         previous_output: outpoint.clone(),
8778                                                                                         script_sig: Script::new(),
8779                                                                                         sequence: *to_self_delay as u32,
8780                                                                                         witness: Vec::new(),
8781                                                                                 };
8782                                                                                 let outp = TxOut {
8783                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8784                                                                                         value: output.value,
8785                                                                                 };
8786                                                                                 let mut spend_tx = Transaction {
8787                                                                                         version: 2,
8788                                                                                         lock_time: 0,
8789                                                                                         input: vec![input],
8790                                                                                         output: vec![outp],
8791                                                                                 };
8792                                                                                 let secp_ctx = Secp256k1::new();
8793                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
8794                                                                                 let local_delaysig = secp_ctx.sign(&sighash, key);
8795                                                                                 spend_tx.input[0].witness.push(local_delaysig.serialize_der(&secp_ctx).to_vec());
8796                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8797                                                                                 spend_tx.input[0].witness.push(vec!(0));
8798                                                                                 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
8799                                                                                 txn.push(spend_tx);
8800                                                                         },
8801                                                                         SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
8802                                                                                 let secp_ctx = Secp256k1::new();
8803                                                                                 let input = TxIn {
8804                                                                                         previous_output: outpoint.clone(),
8805                                                                                         script_sig: Script::new(),
8806                                                                                         sequence: 0,
8807                                                                                         witness: Vec::new(),
8808                                                                                 };
8809                                                                                 let outp = TxOut {
8810                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8811                                                                                         value: output.value,
8812                                                                                 };
8813                                                                                 let mut spend_tx = Transaction {
8814                                                                                         version: 2,
8815                                                                                         lock_time: 0,
8816                                                                                         input: vec![input],
8817                                                                                         output: vec![outp.clone()],
8818                                                                                 };
8819                                                                                 let secret = {
8820                                                                                         match ExtendedPrivKey::new_master(&secp_ctx, Network::Testnet, &$node.node_seed) {
8821                                                                                                 Ok(master_key) => {
8822                                                                                                         match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx)) {
8823                                                                                                                 Ok(key) => key,
8824                                                                                                                 Err(_) => panic!("Your RNG is busted"),
8825                                                                                                         }
8826                                                                                                 }
8827                                                                                                 Err(_) => panic!("Your rng is busted"),
8828                                                                                         }
8829                                                                                 };
8830                                                                                 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
8831                                                                                 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
8832                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8833                                                                                 let sig = secp_ctx.sign(&sighash, &secret.secret_key);
8834                                                                                 spend_tx.input[0].witness.push(sig.serialize_der(&secp_ctx).to_vec());
8835                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8836                                                                                 spend_tx.input[0].witness.push(pubkey.serialize().to_vec());
8837                                                                                 txn.push(spend_tx);
8838                                                                         },
8839                                                                 }
8840                                                         }
8841                                                 },
8842                                                 _ => panic!("Unexpected event"),
8843                                         };
8844                                 }
8845                                 txn
8846                         }
8847                 }
8848         }
8849
8850         #[test]
8851         fn test_claim_sizeable_push_msat() {
8852                 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
8853                 let nodes = create_network(2);
8854
8855                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8856                 nodes[1].node.force_close_channel(&chan.2);
8857                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8858                 match events[0] {
8859                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8860                         _ => panic!("Unexpected event"),
8861                 }
8862                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8863                 assert_eq!(node_txn.len(), 1);
8864                 check_spends!(node_txn[0], chan.3.clone());
8865                 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
8866
8867                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8868                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8869                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8870                 assert_eq!(spend_txn.len(), 1);
8871                 check_spends!(spend_txn[0], node_txn[0].clone());
8872         }
8873
8874         #[test]
8875         fn test_claim_on_remote_sizeable_push_msat() {
8876                 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8877                 // to_remote output is encumbered by a P2WPKH
8878
8879                 let nodes = create_network(2);
8880
8881                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8882                 nodes[0].node.force_close_channel(&chan.2);
8883                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8884                 match events[0] {
8885                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8886                         _ => panic!("Unexpected event"),
8887                 }
8888                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8889                 assert_eq!(node_txn.len(), 1);
8890                 check_spends!(node_txn[0], chan.3.clone());
8891                 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
8892
8893                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8894                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8895                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8896                 match events[0] {
8897                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8898                         _ => panic!("Unexpected event"),
8899                 }
8900                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8901                 assert_eq!(spend_txn.len(), 2);
8902                 assert_eq!(spend_txn[0], spend_txn[1]);
8903                 check_spends!(spend_txn[0], node_txn[0].clone());
8904         }
8905
8906         #[test]
8907         fn test_claim_on_remote_revoked_sizeable_push_msat() {
8908                 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8909                 // to_remote output is encumbered by a P2WPKH
8910
8911                 let nodes = create_network(2);
8912
8913                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
8914                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8915                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
8916                 assert_eq!(revoked_local_txn[0].input.len(), 1);
8917                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8918
8919                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8920                 let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8921                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
8922                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8923                 match events[0] {
8924                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8925                         _ => panic!("Unexpected event"),
8926                 }
8927                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8928                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8929                 assert_eq!(spend_txn.len(), 4);
8930                 assert_eq!(spend_txn[0], spend_txn[2]); // to_remote output on revoked remote commitment_tx
8931                 check_spends!(spend_txn[0], revoked_local_txn[0].clone());
8932                 assert_eq!(spend_txn[1], spend_txn[3]); // to_local output on local commitment tx
8933                 check_spends!(spend_txn[1], node_txn[0].clone());
8934         }
8935
8936         #[test]
8937         fn test_static_spendable_outputs_preimage_tx() {
8938                 let nodes = create_network(2);
8939
8940                 // Create some initial channels
8941                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8942
8943                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8944
8945                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8946                 assert_eq!(commitment_tx[0].input.len(), 1);
8947                 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
8948
8949                 // Settle A's commitment tx on B's chain
8950                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8951                 assert!(nodes[1].node.claim_funds(payment_preimage));
8952                 check_added_monitors!(nodes[1], 1);
8953                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
8954                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8955                 match events[0] {
8956                         MessageSendEvent::UpdateHTLCs { .. } => {},
8957                         _ => panic!("Unexpected event"),
8958                 }
8959                 match events[1] {
8960                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8961                         _ => panic!("Unexepected event"),
8962                 }
8963
8964                 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
8965                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 1 (local commitment tx), ChannelMonitor: 2 (1 preimage tx) * 2 (block-rescan)
8966                 check_spends!(node_txn[0], commitment_tx[0].clone());
8967                 assert_eq!(node_txn[0], node_txn[2]);
8968                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8969                 check_spends!(node_txn[1], chan_1.3.clone());
8970
8971                 let spend_txn = check_spendable_outputs!(nodes[1], 1); // , 0, 0, 1, 1);
8972                 assert_eq!(spend_txn.len(), 2);
8973                 assert_eq!(spend_txn[0], spend_txn[1]);
8974                 check_spends!(spend_txn[0], node_txn[0].clone());
8975         }
8976
8977         #[test]
8978         fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
8979                 let nodes = create_network(2);
8980
8981                 // Create some initial channels
8982                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8983
8984                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8985                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
8986                 assert_eq!(revoked_local_txn[0].input.len(), 1);
8987                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
8988
8989                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8990
8991                 let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8992                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
8993                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8994                 match events[0] {
8995                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8996                         _ => panic!("Unexpected event"),
8997                 }
8998                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8999                 assert_eq!(node_txn.len(), 3);
9000                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]);
9001                 assert_eq!(node_txn[0].input.len(), 2);
9002                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
9003
9004                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9005                 assert_eq!(spend_txn.len(), 2);
9006                 assert_eq!(spend_txn[0], spend_txn[1]);
9007                 check_spends!(spend_txn[0], node_txn[0].clone());
9008         }
9009
9010         #[test]
9011         fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
9012                 let nodes = create_network(2);
9013
9014                 // Create some initial channels
9015                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9016
9017                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9018                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9019                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9020                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9021
9022                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9023
9024                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9025                 // A will generate HTLC-Timeout from revoked commitment tx
9026                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9027                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9028                 match events[0] {
9029                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9030                         _ => panic!("Unexpected event"),
9031                 }
9032                 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9033                 assert_eq!(revoked_htlc_txn.len(), 3);
9034                 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
9035                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
9036                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9037                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
9038                 check_spends!(revoked_htlc_txn[1], chan_1.3.clone());
9039
9040                 // B will generate justice tx from A's revoked commitment/HTLC tx
9041                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
9042                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9043                 match events[0] {
9044                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9045                         _ => panic!("Unexpected event"),
9046                 }
9047
9048                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9049                 assert_eq!(node_txn.len(), 4);
9050                 assert_eq!(node_txn[3].input.len(), 1);
9051                 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
9052
9053                 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
9054                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9055                 assert_eq!(spend_txn.len(), 3);
9056                 assert_eq!(spend_txn[0], spend_txn[1]);
9057                 check_spends!(spend_txn[0], node_txn[0].clone());
9058                 check_spends!(spend_txn[2], node_txn[3].clone());
9059         }
9060
9061         #[test]
9062         fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
9063                 let nodes = create_network(2);
9064
9065                 // Create some initial channels
9066                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9067
9068                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9069                 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9070                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9071                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9072
9073                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9074
9075                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9076                 // B will generate HTLC-Success from revoked commitment tx
9077                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9078                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9079                 match events[0] {
9080                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9081                         _ => panic!("Unexpected event"),
9082                 }
9083                 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9084
9085                 assert_eq!(revoked_htlc_txn.len(), 3);
9086                 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
9087                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
9088                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9089                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
9090
9091                 // A will generate justice tx from B's revoked commitment/HTLC tx
9092                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
9093                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9094                 match events[0] {
9095                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9096                         _ => panic!("Unexpected event"),
9097                 }
9098
9099                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9100                 assert_eq!(node_txn.len(), 4);
9101                 assert_eq!(node_txn[3].input.len(), 1);
9102                 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
9103
9104                 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
9105                 let spend_txn = check_spendable_outputs!(nodes[0], 1);
9106                 assert_eq!(spend_txn.len(), 5);
9107                 assert_eq!(spend_txn[0], spend_txn[2]);
9108                 assert_eq!(spend_txn[1], spend_txn[3]);
9109                 check_spends!(spend_txn[0], revoked_local_txn[0].clone()); // spending to_remote output from revoked local tx
9110                 check_spends!(spend_txn[1], node_txn[2].clone()); // spending justice tx output from revoked local tx htlc received output
9111                 check_spends!(spend_txn[4], node_txn[3].clone()); // spending justice tx output on htlc success tx
9112         }
9113
9114         #[test]
9115         fn test_onchain_to_onchain_claim() {
9116                 // Test that in case of channel closure, we detect the state of output thanks to
9117                 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
9118                 // First, have C claim an HTLC against its own latest commitment transaction.
9119                 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
9120                 // channel.
9121                 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
9122                 // gets broadcast.
9123
9124                 let nodes = create_network(3);
9125
9126                 // Create some initial channels
9127                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9128                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
9129
9130                 // Rebalance the network a bit by relaying one payment through all the channels ...
9131                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
9132                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
9133
9134                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
9135                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9136                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
9137                 check_spends!(commitment_tx[0], chan_2.3.clone());
9138                 nodes[2].node.claim_funds(payment_preimage);
9139                 check_added_monitors!(nodes[2], 1);
9140                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9141                 assert!(updates.update_add_htlcs.is_empty());
9142                 assert!(updates.update_fail_htlcs.is_empty());
9143                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
9144                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9145
9146                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
9147                 let events = nodes[2].node.get_and_clear_pending_msg_events();
9148                 assert_eq!(events.len(), 1);
9149                 match events[0] {
9150                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9151                         _ => panic!("Unexpected event"),
9152                 }
9153
9154                 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
9155                 assert_eq!(c_txn.len(), 3);
9156                 assert_eq!(c_txn[0], c_txn[2]);
9157                 assert_eq!(commitment_tx[0], c_txn[1]);
9158                 check_spends!(c_txn[1], chan_2.3.clone());
9159                 check_spends!(c_txn[2], c_txn[1].clone());
9160                 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
9161                 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9162                 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
9163                 assert_eq!(c_txn[0].lock_time, 0); // Success tx
9164
9165                 // 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
9166                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
9167                 {
9168                         let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9169                         assert_eq!(b_txn.len(), 4);
9170                         assert_eq!(b_txn[0], b_txn[3]);
9171                         check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
9172                         check_spends!(b_txn[2], b_txn[1].clone()); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
9173                         assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9174                         assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
9175                         assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
9176                         check_spends!(b_txn[0], c_txn[1].clone()); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
9177                         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9178                         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
9179                         assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
9180                         b_txn.clear();
9181                 }
9182                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
9183                 check_added_monitors!(nodes[1], 1);
9184                 match msg_events[0] {
9185                         MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
9186                         _ => panic!("Unexpected event"),
9187                 }
9188                 match msg_events[1] {
9189                         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, .. } } => {
9190                                 assert!(update_add_htlcs.is_empty());
9191                                 assert!(update_fail_htlcs.is_empty());
9192                                 assert_eq!(update_fulfill_htlcs.len(), 1);
9193                                 assert!(update_fail_malformed_htlcs.is_empty());
9194                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
9195                         },
9196                         _ => panic!("Unexpected event"),
9197                 };
9198                 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
9199                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9200                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
9201                 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9202                 assert_eq!(b_txn.len(), 3);
9203                 check_spends!(b_txn[1], chan_1.3); // Local commitment tx, issued by ChannelManager
9204                 assert_eq!(b_txn[0], b_txn[2]); // HTLC-Success tx, issued by ChannelMonitor, * 2 due to block rescan
9205                 check_spends!(b_txn[0], commitment_tx[0].clone());
9206                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9207                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
9208                 assert_eq!(b_txn[2].lock_time, 0); // Success tx
9209                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
9210                 match msg_events[0] {
9211                         MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
9212                         _ => panic!("Unexpected event"),
9213                 }
9214         }
9215
9216         #[test]
9217         fn test_duplicate_payment_hash_one_failure_one_success() {
9218                 // Topology : A --> B --> C
9219                 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
9220                 let mut nodes = create_network(3);
9221
9222                 create_announced_chan_between_nodes(&nodes, 0, 1);
9223                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
9224
9225                 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
9226                 *nodes[0].network_payment_count.borrow_mut() -= 1;
9227                 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
9228
9229                 let commitment_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
9230                 assert_eq!(commitment_txn[0].input.len(), 1);
9231                 check_spends!(commitment_txn[0], chan_2.3.clone());
9232
9233                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9234                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
9235                 let htlc_timeout_tx;
9236                 { // Extract one of the two HTLC-Timeout transaction
9237                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9238                         assert_eq!(node_txn.len(), 7);
9239                         assert_eq!(node_txn[0], node_txn[5]);
9240                         assert_eq!(node_txn[1], node_txn[6]);
9241                         check_spends!(node_txn[0], commitment_txn[0].clone());
9242                         assert_eq!(node_txn[0].input.len(), 1);
9243                         check_spends!(node_txn[1], commitment_txn[0].clone());
9244                         assert_eq!(node_txn[1].input.len(), 1);
9245                         assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
9246                         check_spends!(node_txn[2], chan_2.3.clone());
9247                         check_spends!(node_txn[3], node_txn[2].clone());
9248                         check_spends!(node_txn[4], node_txn[2].clone());
9249                         htlc_timeout_tx = node_txn[1].clone();
9250                 }
9251
9252                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9253                 match events[0] {
9254                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9255                         _ => panic!("Unexepected event"),
9256                 }
9257
9258                 nodes[2].node.claim_funds(our_payment_preimage);
9259                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
9260                 check_added_monitors!(nodes[2], 2);
9261                 let events = nodes[2].node.get_and_clear_pending_msg_events();
9262                 match events[0] {
9263                         MessageSendEvent::UpdateHTLCs { .. } => {},
9264                         _ => panic!("Unexpected event"),
9265                 }
9266                 match events[1] {
9267                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9268                         _ => panic!("Unexepected event"),
9269                 }
9270                 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9271                 assert_eq!(htlc_success_txn.len(), 5);
9272                 check_spends!(htlc_success_txn[2], chan_2.3.clone());
9273                 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
9274                 assert_eq!(htlc_success_txn[0].input.len(), 1);
9275                 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9276                 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
9277                 assert_eq!(htlc_success_txn[1].input.len(), 1);
9278                 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9279                 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
9280                 check_spends!(htlc_success_txn[0], commitment_txn[0].clone());
9281                 check_spends!(htlc_success_txn[1], commitment_txn[0].clone());
9282
9283                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
9284                 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9285                 assert!(htlc_updates.update_add_htlcs.is_empty());
9286                 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
9287                 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
9288                 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
9289                 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
9290                 check_added_monitors!(nodes[1], 1);
9291
9292                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]).unwrap();
9293                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9294                 {
9295                         commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
9296                         let events = nodes[0].node.get_and_clear_pending_msg_events();
9297                         assert_eq!(events.len(), 1);
9298                         match events[0] {
9299                                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
9300                                 },
9301                                 _ => { panic!("Unexpected event"); }
9302                         }
9303                 }
9304                 let events = nodes[0].node.get_and_clear_pending_events();
9305                 match events[0] {
9306                         Event::PaymentFailed { ref payment_hash, .. } => {
9307                                 assert_eq!(*payment_hash, duplicate_payment_hash);
9308                         }
9309                         _ => panic!("Unexpected event"),
9310                 }
9311
9312                 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
9313                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
9314                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9315                 assert!(updates.update_add_htlcs.is_empty());
9316                 assert!(updates.update_fail_htlcs.is_empty());
9317                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
9318                 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
9319                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9320                 check_added_monitors!(nodes[1], 1);
9321
9322                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
9323                 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
9324
9325                 let events = nodes[0].node.get_and_clear_pending_events();
9326                 match events[0] {
9327                         Event::PaymentSent { ref payment_preimage } => {
9328                                 assert_eq!(*payment_preimage, our_payment_preimage);
9329                         }
9330                         _ => panic!("Unexpected event"),
9331                 }
9332         }
9333
9334         #[test]
9335         fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
9336                 let nodes = create_network(2);
9337
9338                 // Create some initial channels
9339                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9340
9341                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
9342                 let local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9343                 assert_eq!(local_txn[0].input.len(), 1);
9344                 check_spends!(local_txn[0], chan_1.3.clone());
9345
9346                 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
9347                 nodes[1].node.claim_funds(payment_preimage);
9348                 check_added_monitors!(nodes[1], 1);
9349                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9350                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
9351                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9352                 match events[0] {
9353                         MessageSendEvent::UpdateHTLCs { .. } => {},
9354                         _ => panic!("Unexpected event"),
9355                 }
9356                 match events[1] {
9357                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9358                         _ => panic!("Unexepected event"),
9359                 }
9360                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9361                 assert_eq!(node_txn[0].input.len(), 1);
9362                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9363                 check_spends!(node_txn[0], local_txn[0].clone());
9364
9365                 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
9366                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9367                 assert_eq!(spend_txn.len(), 2);
9368                 check_spends!(spend_txn[0], node_txn[0].clone());
9369                 check_spends!(spend_txn[1], node_txn[2].clone());
9370         }
9371
9372         #[test]
9373         fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
9374                 let nodes = create_network(2);
9375
9376                 // Create some initial channels
9377                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9378
9379                 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
9380                 let local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9381                 assert_eq!(local_txn[0].input.len(), 1);
9382                 check_spends!(local_txn[0], chan_1.3.clone());
9383
9384                 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
9385                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9386                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
9387                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9388                 match events[0] {
9389                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9390                         _ => panic!("Unexepected event"),
9391                 }
9392                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9393                 assert_eq!(node_txn[0].input.len(), 1);
9394                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9395                 check_spends!(node_txn[0], local_txn[0].clone());
9396
9397                 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
9398                 let spend_txn = check_spendable_outputs!(nodes[0], 1);
9399                 assert_eq!(spend_txn.len(), 8);
9400                 assert_eq!(spend_txn[0], spend_txn[2]);
9401                 assert_eq!(spend_txn[0], spend_txn[4]);
9402                 assert_eq!(spend_txn[0], spend_txn[6]);
9403                 assert_eq!(spend_txn[1], spend_txn[3]);
9404                 assert_eq!(spend_txn[1], spend_txn[5]);
9405                 assert_eq!(spend_txn[1], spend_txn[7]);
9406                 check_spends!(spend_txn[0], local_txn[0].clone());
9407                 check_spends!(spend_txn[1], node_txn[0].clone());
9408         }
9409
9410         #[test]
9411         fn test_static_output_closing_tx() {
9412                 let nodes = create_network(2);
9413
9414                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
9415
9416                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
9417                 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
9418
9419                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9420                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
9421                 let spend_txn = check_spendable_outputs!(nodes[0], 2);
9422                 assert_eq!(spend_txn.len(), 1);
9423                 check_spends!(spend_txn[0], closing_tx.clone());
9424
9425                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
9426                 let spend_txn = check_spendable_outputs!(nodes[1], 2);
9427                 assert_eq!(spend_txn.len(), 1);
9428                 check_spends!(spend_txn[0], closing_tx);
9429         }
9430
9431         fn run_onion_failure_test<F1,F2>(_name: &str, test_case: u8, nodes: &Vec<Node>, route: &Route, payment_hash: &PaymentHash, callback_msg: F1, callback_node: F2, expected_retryable: bool, expected_error_code: Option<u16>, expected_channel_update: Option<HTLCFailChannelUpdate>)
9432                 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
9433                                         F2: FnMut(),
9434         {
9435                 run_onion_failure_test_with_fail_intercept(_name, test_case, nodes, route, payment_hash, callback_msg, |_|{}, callback_node, expected_retryable, expected_error_code, expected_channel_update);
9436         }
9437
9438         // test_case
9439         // 0: node1 fail backward
9440         // 1: final node fail backward
9441         // 2: payment completed but the user reject the payment
9442         // 3: final node fail backward (but tamper onion payloads from node0)
9443         // 100: trigger error in the intermediate node and tamper returnning fail_htlc
9444         // 200: trigger error in the final node and tamper returnning fail_htlc
9445         fn run_onion_failure_test_with_fail_intercept<F1,F2,F3>(_name: &str, test_case: u8, nodes: &Vec<Node>, route: &Route, payment_hash: &PaymentHash, mut callback_msg: F1, mut callback_fail: F2, mut callback_node: F3, expected_retryable: bool, expected_error_code: Option<u16>, expected_channel_update: Option<HTLCFailChannelUpdate>)
9446                 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
9447                                         F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
9448                                         F3: FnMut(),
9449         {
9450                 use ln::msgs::HTLCFailChannelUpdate;
9451
9452                 // reset block height
9453                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9454                 for ix in 0..nodes.len() {
9455                         nodes[ix].chain_monitor.block_connected_checked(&header, 1, &Vec::new()[..], &[0; 0]);
9456                 }
9457
9458                 macro_rules! expect_event {
9459                         ($node: expr, $event_type: path) => {{
9460                                 let events = $node.node.get_and_clear_pending_events();
9461                                 assert_eq!(events.len(), 1);
9462                                 match events[0] {
9463                                         $event_type { .. } => {},
9464                                         _ => panic!("Unexpected event"),
9465                                 }
9466                         }}
9467                 }
9468
9469                 macro_rules! expect_htlc_forward {
9470                         ($node: expr) => {{
9471                                 expect_event!($node, Event::PendingHTLCsForwardable);
9472                                 $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
9473                                 $node.node.process_pending_htlc_forwards();
9474                         }}
9475                 }
9476
9477                 // 0 ~~> 2 send payment
9478                 nodes[0].node.send_payment(route.clone(), payment_hash.clone()).unwrap();
9479                 check_added_monitors!(nodes[0], 1);
9480                 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
9481                 // temper update_add (0 => 1)
9482                 let mut update_add_0 = update_0.update_add_htlcs[0].clone();
9483                 if test_case == 0 || test_case == 3 || test_case == 100 {
9484                         callback_msg(&mut update_add_0);
9485                         callback_node();
9486                 }
9487                 // 0 => 1 update_add & CS
9488                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0).unwrap();
9489                 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
9490
9491                 let update_1_0 = match test_case {
9492                         0|100 => { // intermediate node failure; fail backward to 0
9493                                 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9494                                 assert!(update_1_0.update_fail_htlcs.len()+update_1_0.update_fail_malformed_htlcs.len()==1 && (update_1_0.update_fail_htlcs.len()==1 || update_1_0.update_fail_malformed_htlcs.len()==1));
9495                                 update_1_0
9496                         },
9497                         1|2|3|200 => { // final node failure; forwarding to 2
9498                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9499                                 // forwarding on 1
9500                                 if test_case != 200 {
9501                                         callback_node();
9502                                 }
9503                                 expect_htlc_forward!(&nodes[1]);
9504
9505                                 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
9506                                 check_added_monitors!(&nodes[1], 1);
9507                                 assert_eq!(update_1.update_add_htlcs.len(), 1);
9508                                 // tamper update_add (1 => 2)
9509                                 let mut update_add_1 = update_1.update_add_htlcs[0].clone();
9510                                 if test_case != 3 && test_case != 200 {
9511                                         callback_msg(&mut update_add_1);
9512                                 }
9513
9514                                 // 1 => 2
9515                                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1).unwrap();
9516                                 commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
9517
9518                                 if test_case == 2 || test_case == 200 {
9519                                         expect_htlc_forward!(&nodes[2]);
9520                                         expect_event!(&nodes[2], Event::PaymentReceived);
9521                                         callback_node();
9522                                 }
9523
9524                                 let update_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9525                                 if test_case == 2 || test_case == 200 {
9526                                         check_added_monitors!(&nodes[2], 1);
9527                                 }
9528                                 assert!(update_2_1.update_fail_htlcs.len() == 1);
9529
9530                                 let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
9531                                 if test_case == 200 {
9532                                         callback_fail(&mut fail_msg);
9533                                 }
9534
9535                                 // 2 => 1
9536                                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg).unwrap();
9537                                 commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true, true);
9538
9539                                 // backward fail on 1
9540                                 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9541                                 assert!(update_1_0.update_fail_htlcs.len() == 1);
9542                                 update_1_0
9543                         },
9544                         _ => unreachable!(),
9545                 };
9546
9547                 // 1 => 0 commitment_signed_dance
9548                 if update_1_0.update_fail_htlcs.len() > 0 {
9549                         let mut fail_msg = update_1_0.update_fail_htlcs[0].clone();
9550                         if test_case == 100 {
9551                                 callback_fail(&mut fail_msg);
9552                         }
9553                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg).unwrap();
9554                 } else {
9555                         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]).unwrap();
9556                 };
9557
9558                 commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
9559
9560                 let events = nodes[0].node.get_and_clear_pending_events();
9561                 assert_eq!(events.len(), 1);
9562                 if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code } = &events[0] {
9563                         assert_eq!(*rejected_by_dest, !expected_retryable);
9564                         assert_eq!(*error_code, expected_error_code);
9565                 } else {
9566                         panic!("Uexpected event");
9567                 }
9568
9569                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9570                 if expected_channel_update.is_some() {
9571                         assert_eq!(events.len(), 1);
9572                         match events[0] {
9573                                 MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
9574                                         match update {
9575                                                 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {
9576                                                         if let HTLCFailChannelUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
9577                                                                 panic!("channel_update not found!");
9578                                                         }
9579                                                 },
9580                                                 &HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
9581                                                         if let HTLCFailChannelUpdate::ChannelClosed { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
9582                                                                 assert!(*short_channel_id == *expected_short_channel_id);
9583                                                                 assert!(*is_permanent == *expected_is_permanent);
9584                                                         } else {
9585                                                                 panic!("Unexpected message event");
9586                                                         }
9587                                                 },
9588                                                 &HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
9589                                                         if let HTLCFailChannelUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
9590                                                                 assert!(*node_id == *expected_node_id);
9591                                                                 assert!(*is_permanent == *expected_is_permanent);
9592                                                         } else {
9593                                                                 panic!("Unexpected message event");
9594                                                         }
9595                                                 },
9596                                         }
9597                                 },
9598                                 _ => panic!("Unexpected message event"),
9599                         }
9600                 } else {
9601                         assert_eq!(events.len(), 0);
9602                 }
9603         }
9604
9605         impl msgs::ChannelUpdate {
9606                 fn dummy() -> msgs::ChannelUpdate {
9607                         use secp256k1::ffi::Signature as FFISignature;
9608                         use secp256k1::Signature;
9609                         msgs::ChannelUpdate {
9610                                 signature: Signature::from(FFISignature::new()),
9611                                 contents: msgs::UnsignedChannelUpdate {
9612                                         chain_hash: Sha256dHash::from_data(&vec![0u8][..]),
9613                                         short_channel_id: 0,
9614                                         timestamp: 0,
9615                                         flags: 0,
9616                                         cltv_expiry_delta: 0,
9617                                         htlc_minimum_msat: 0,
9618                                         fee_base_msat: 0,
9619                                         fee_proportional_millionths: 0,
9620                                         excess_data: vec![],
9621                                 }
9622                         }
9623                 }
9624         }
9625
9626         #[test]
9627         fn test_onion_failure() {
9628                 use ln::msgs::ChannelUpdate;
9629                 use ln::channelmanager::CLTV_FAR_FAR_AWAY;
9630                 use secp256k1;
9631
9632                 const BADONION: u16 = 0x8000;
9633                 const PERM: u16 = 0x4000;
9634                 const NODE: u16 = 0x2000;
9635                 const UPDATE: u16 = 0x1000;
9636
9637                 let mut nodes = create_network(3);
9638                 for node in nodes.iter() {
9639                         *node.keys_manager.override_session_priv.lock().unwrap() = Some(SecretKey::from_slice(&Secp256k1::without_caps(), &[3; 32]).unwrap());
9640                 }
9641                 let channels = [create_announced_chan_between_nodes(&nodes, 0, 1), create_announced_chan_between_nodes(&nodes, 1, 2)];
9642                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
9643                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap();
9644                 // positve case
9645                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000);
9646
9647                 // intermediate node failure
9648                 run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, |msg| {
9649                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9650                         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
9651                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9652                         let (mut onion_payloads, _htlc_msat, _htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height).unwrap();
9653                         onion_payloads[0].realm = 3;
9654                         msg.onion_routing_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
9655                 }, ||{}, true, Some(PERM|1), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));//XXX incremented channels idx here
9656
9657                 // final node failure
9658                 run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, |msg| {
9659                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9660                         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
9661                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9662                         let (mut onion_payloads, _htlc_msat, _htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height).unwrap();
9663                         onion_payloads[1].realm = 3;
9664                         msg.onion_routing_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
9665                 }, ||{}, false, Some(PERM|1), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
9666
9667                 // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
9668                 // receiving simulated fail messages
9669                 // intermediate node failure
9670                 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
9671                         // trigger error
9672                         msg.amount_msat -= 1;
9673                 }, |msg| {
9674                         // and tamper returing error message
9675                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9676                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9677                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], NODE|2, &[0;0]);
9678                 }, ||{}, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: false}));
9679
9680                 // final node failure
9681                 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
9682                         // and tamper returing error message
9683                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9684                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9685                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], NODE|2, &[0;0]);
9686                 }, ||{
9687                         nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
9688                 }, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: false}));
9689
9690                 // intermediate node failure
9691                 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
9692                         msg.amount_msat -= 1;
9693                 }, |msg| {
9694                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9695                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9696                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|2, &[0;0]);
9697                 }, ||{}, true, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
9698
9699                 // final node failure
9700                 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
9701                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9702                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9703                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|2, &[0;0]);
9704                 }, ||{
9705                         nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
9706                 }, false, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
9707
9708                 // intermediate node failure
9709                 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
9710                         msg.amount_msat -= 1;
9711                 }, |msg| {
9712                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9713                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9714                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|3, &[0;0]);
9715                 }, ||{
9716                         nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
9717                 }, true, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
9718
9719                 // final node failure
9720                 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
9721                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9722                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9723                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|3, &[0;0]);
9724                 }, ||{
9725                         nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
9726                 }, false, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
9727
9728                 run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
9729                         Some(BADONION|PERM|4), None);
9730
9731                 run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
9732                         Some(BADONION|PERM|5), None);
9733
9734                 run_onion_failure_test("invalid_onion_key", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.public_key = Err(secp256k1::Error::InvalidPublicKey);}, ||{}, true,
9735                         Some(BADONION|PERM|6), None);
9736
9737                 run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
9738                         msg.amount_msat -= 1;
9739                 }, |msg| {
9740                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9741                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9742                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], UPDATE|7, &ChannelUpdate::dummy().encode_with_len()[..]);
9743                 }, ||{}, true, Some(UPDATE|7), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
9744
9745                 run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
9746                         msg.amount_msat -= 1;
9747                 }, |msg| {
9748                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9749                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9750                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|8, &[0;0]);
9751                         // short_channel_id from the processing node
9752                 }, ||{}, true, Some(PERM|8), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
9753
9754                 run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
9755                         msg.amount_msat -= 1;
9756                 }, |msg| {
9757                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9758                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9759                         msg.reason = ChannelManager::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|9, &[0;0]);
9760                         // short_channel_id from the processing node
9761                 }, ||{}, true, Some(PERM|9), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
9762
9763                 let mut bogus_route = route.clone();
9764                 bogus_route.hops[1].short_channel_id -= 1;
9765                 run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(PERM|10),
9766                   Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: bogus_route.hops[1].short_channel_id, is_permanent:true}));
9767
9768                 let amt_to_forward = nodes[1].node.channel_state.lock().unwrap().by_id.get(&channels[1].2).unwrap().get_their_htlc_minimum_msat() - 1;
9769                 let mut bogus_route = route.clone();
9770                 let route_len = bogus_route.hops.len();
9771                 bogus_route.hops[route_len-1].fee_msat = amt_to_forward;
9772                 run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(UPDATE|11), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
9773
9774                 //TODO: with new config API, we will be able to generate both valid and
9775                 //invalid channel_update cases.
9776                 run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, |msg| {
9777                         msg.amount_msat -= 1;
9778                 }, || {}, true, Some(UPDATE|12), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
9779
9780                 run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, |msg| {
9781                         // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
9782                         msg.cltv_expiry -= 1;
9783                 }, || {}, true, Some(UPDATE|13), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
9784
9785                 run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, |msg| {
9786                         let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - HTLC_FAIL_TIMEOUT_BLOCKS + 1;
9787                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9788                         nodes[1].chain_monitor.block_connected_checked(&header, height, &Vec::new()[..], &[0; 0]);
9789                 }, ||{}, true, Some(UPDATE|14), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
9790
9791                 run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, |_| {}, || {
9792                         nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
9793                 }, false, Some(PERM|15), None);
9794
9795                 run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, |msg| {
9796                         let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - HTLC_FAIL_TIMEOUT_BLOCKS + 1;
9797                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9798                         nodes[2].chain_monitor.block_connected_checked(&header, height, &Vec::new()[..], &[0; 0]);
9799                 }, || {}, true, Some(17), None);
9800
9801                 run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, |_| {}, || {
9802                         for (_, mut pending_forwards) in nodes[1].node.channel_state.lock().unwrap().borrow_parts().forward_htlcs.iter_mut() {
9803                                 for f in pending_forwards.iter_mut() {
9804                                         f.forward_info.outgoing_cltv_value += 1;
9805                                 }
9806                         }
9807                 }, true, Some(18), None);
9808
9809                 run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, |_| {}, || {
9810                         // violate amt_to_forward > msg.amount_msat
9811                         for (_, mut pending_forwards) in nodes[1].node.channel_state.lock().unwrap().borrow_parts().forward_htlcs.iter_mut() {
9812                                 for f in pending_forwards.iter_mut() {
9813                                         f.forward_info.amt_to_forward -= 1;
9814                                 }
9815                         }
9816                 }, true, Some(19), None);
9817
9818                 run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, |_| {}, || {
9819                         // disconnect event to the channel between nodes[1] ~ nodes[2]
9820                         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9821                         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9822                 }, true, Some(UPDATE|20), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
9823                 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9824
9825                 run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, |msg| {
9826                         let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
9827                         let mut route = route.clone();
9828                         let height = 1;
9829                         route.hops[1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.hops[0].cltv_expiry_delta + 1;
9830                         let onion_keys = ChannelManager::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
9831                         let (onion_payloads, _, htlc_cltv) = ChannelManager::build_onion_payloads(&route, height).unwrap();
9832                         let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
9833                         msg.cltv_expiry = htlc_cltv;
9834                         msg.onion_routing_packet = onion_packet;
9835                 }, ||{}, true, Some(21), None);
9836         }
9837 }